Build a Guildly bot
A bot is a member of a server run by your own program. It reads and sends messages, answers slash commands, and reacts to buttons and menus.
Quickstart
You need Node.js 22 or later. The SDK is one file with no dependencies.
1. Create the bot
Open Guildly, go to User settings, then My bots, and create a bot. Copy its token and application ID. You can have up to 10 bots.
2. Get the SDK
mkdir my-bot
cd my-bot
curl -O https://guildly.octail.net/sdk/guildly.js
curl -O https://guildly.octail.net/sdk/guildly.d.ts
npm init -y
npm pkg set type=module In Windows PowerShell, type curl.exe instead of curl.
3. Write the bot
// bot.js
import { Client } from "./guildly.js";
const client = new Client();
client.on("ready", async () => {
await client.commands.set([{ name: "ping", description: "Check that the bot is awake" }]);
console.log("Ready");
});
client.on("interactionCreate", async (interaction) => {
if (interaction.commandName === "ping") await interaction.reply("Pong!");
});
client.on("error", (error) => console.error(error.message));
await client.login(process.env.GUILDLY_BOT_TOKEN); 4. Run it
# macOS and Linux
GUILDLY_BOT_TOKEN="your bot token" node bot.js
# Windows PowerShell
$env:GUILDLY_BOT_TOKEN = "your bot token"
node bot.js Add the bot to a server, type /ping in a
channel it can see, and it answers.
Add it to a server
Anyone with the Manage server permission can open Server settings, then Bots, choose Add bot, and paste the application ID or an invite link. They pick the permissions the bot gets.
The invite link for your bot is:
https://guildly-app.octail.net/?addbot=<application id> - A private bot can be added only by its owner. Make it public in My bots to let others add it.
- Nobody can give a bot a permission they do not hold themselves.
- The bot gets a role with its name. Guildly manages that role, so it cannot be assigned or deleted by hand.
- To remove a bot, kick it like any member. Its role goes with it.
- A bot that is banned from a server cannot be added to it.
Messages
A bot receives the messages of every channel it can view, with their full text, and sends them under the same permissions and channel rules as a person.
client.on("messageCreate", async (message) => {
// Never answer yourself or another bot: two bots can loop for ever.
if (message.authorId === client.user.id || message.authorBot) return;
if (!message.content.startsWith("!echo ")) return;
const text = message.content.slice(6).trim();
if (text) await message.reply(text);
});
Send to a channel with client.channels.send(channelId, body).
The body is text, or an object with content (up to 4,000
characters), embeds, components and
replyToId. At least one of the first three is needed. To copy
a channel's id in the app, right-click it and choose
Copy Channel ID.
Slash commands
People type / at the start of a message to see the commands
of the bots in that channel. A bot's commands are listed where the bot
can view and send. Register them when your bot starts:
await client.commands.set(
[
{
name: "raid",
description: "Announce a raid",
options: [
{ name: "title", description: "What are we doing?", type: "string", required: true },
{
name: "size",
description: "Group size",
type: "integer",
choices: [{ name: "Five", value: 5 }, { name: "Twenty", value: 20 }],
},
{ name: "leader", description: "Who leads", type: "user" },
],
},
],
guildId, // leave out for commands in every server the bot is in
); - Setting commands replaces the whole set: the global one, or one server's. A command whose name is unchanged keeps its id.
- Up to 100 commands in a set. A bot can set a server's commands only while it is in that server.
- A name is 1 to 32 characters from
a-z,0-9,_and-. A description is 1 to 100 characters. - Up to 25 options, with the required ones first.
- Option types:
string,integer,number,boolean,user,channelandrole. string,integerandnumberoptions may offer up to 25choices.
The server checks option types, required options and choices, and that a chosen user, channel or role belongs to the server. For those three your bot receives the id.
Answering commands
Using a command, button or menu sends your bot an interaction. Answer it once, within 15 seconds. If the work takes longer, defer first.
| SDK method | What it does |
|---|---|
reply(body) | Posts a message. Add ephemeral: true to show it only to the person who asked. |
defer() | Shows that the bot is thinking. defer({ ephemeral: true }) keeps the answer private. |
update(body) | Buttons and menus only: changes the message they are on. |
deferUpdate() | Buttons and menus only: accepts the press without changing anything yet. |
editReply(body) | After defer(), sends the answer. Otherwise changes the original response; after update or deferUpdate that is the message with the button or menu. |
followUp(body) | Posts another message. May be ephemeral. The first one after defer() is the answer, and stays private if you deferred privately. |
editReply and followUp work for 15 minutes. In
an edit, what you leave out stays as it is, and an empty list removes
embeds or components. An ephemeral message is not kept, so editing one
replaces all of it.
client.on("interactionCreate", async (interaction) => {
if (interaction.commandName !== "raid") return;
const title = interaction.options.get("title");
const size = interaction.options.get("size") ?? 5; // null when left out
const leader = interaction.options.get("leader") ?? interaction.user.id;
await interaction.defer(); // shows "<bot> is thinking…"
const member = await client.rest.get(`/users/${leader}`);
await interaction.editReply(`**${title}** for ${size}, led by ${member.username}.`);
}); An ephemeral message is never stored. It disappears when the person dismisses it or reloads the app, and it cannot carry buttons or menus. Everything a bot posts this way still needs the bot's own permission in that channel.
If your bot is not connected to the gateway, the person is told at once that the command could not be sent. If it does not answer in time, they see that the bot did not respond.
Buttons and menus
Only bots can send these. A message has up to 5 rows; a row holds 1 to 5 buttons, or one select menu.
await client.channels.send(channelId, {
content: "Are you coming tonight?",
components: [
{
components: [
{ type: "button", style: "success", label: "Yes", customId: "rsvp:yes" },
{ type: "button", style: "secondary", label: "No", customId: "rsvp:no" },
{ type: "button", style: "link", label: "Rules", url: "https://example.com/rules" },
],
},
{
components: [
{
type: "select",
customId: "rsvp:role",
placeholder: "Your role",
options: [
{ label: "Tank", value: "tank" },
{ label: "Healer", value: "healer", description: "Keeps us alive" },
],
},
],
},
],
}); - Button styles:
primary,secondary,success,dangerandlink. - A
linkbutton takes an httpsurland nocustomId. It opens the address and sends your bot nothing. - Other buttons and menus take a
customIdof up to 100 characters, unique within the message. - Button and option labels are up to 80 and 100 characters. An option's
valueanddescriptionare up to 100. - A menu has 1 to 25 options, each with a different
value.minValues(0 to 25) andmaxValues(1 to 25) both default to 1. Aplaceholderis up to 150 characters. - Add
disabled: trueto switch a button or menu off.
client.on("interactionCreate", async (interaction) => {
if (interaction.customId === "rsvp:yes") {
// Changes the message the button is on.
await interaction.update({ content: `${interaction.user.handle} is coming.`, components: [] });
} else if (interaction.customId === "rsvp:no") {
await interaction.reply({ content: "Maybe next time.", ephemeral: true });
} else if (interaction.customId === "rsvp:role") {
await interaction.reply({ content: `Noted: ${interaction.values.join(", ")}`, ephemeral: true });
}
}); Anyone who can use the channel may press a button. Check interaction.user.id or interaction.memberPermissions before doing anything that matters.
Embeds
An embed is a card with a colour bar, a title, text, fields and pictures. Only bots can send them. Each one needs at least a title, description, field, footer or picture.
await client.channels.send(channelId, {
embeds: [
{
title: "Match report",
url: "https://example.com/match/42",
description: "**Blue** beat Red.",
color: 0xffc53d,
fields: [
{ name: "Score", value: "3 : 1", inline: true },
{ name: "Length", value: "34 min", inline: true },
],
footer: { text: "Season 4" },
timestamp: new Date().toISOString(),
},
],
}); | Property | Limit |
|---|---|
| Embeds in a message | 10, with at most 6,000 characters of text in all |
title | 256 characters |
description | 4,096 characters, formatted like a message |
url | https; makes the title a link |
color | A whole number from 0 to 0xFFFFFF |
fields | 25; name 256 and value 1,024 characters; inline puts them in columns |
footer.text | 2,048 characters |
timestamp | An ISO 8601 time with a time zone |
imageUrl, thumbnailUrl | A file uploaded to Guildly (/attachments/<id>), or a GIF or WebP on GIPHY's media hosts (media.giphy.com, media0 to media4.giphy.com, i.giphy.com). Other web addresses are refused. |
To show your own picture, upload it first:
import { readFile } from "node:fs/promises";
const upload = await client.attachments.upload({
filename: "map.png",
contentType: "image/png",
data: await readFile("map.png"),
});
await client.channels.send(channelId, {
embeds: [{ title: "Tonight's map", imageUrl: upload.url }],
}); SDK reference
| Member | What it does |
|---|---|
new Client() | For another installation, pass both baseUrl and gatewayUrl. |
login(token), destroy() | Connect and disconnect. |
setToken(token) | Use the REST API without connecting. |
channels | send(channelId, body), history(channelId, { limit, before }), typing(channelId) |
commands | set(list, guildId?), list(guildId?) |
attachments | upload({ filename, contentType, data }) |
message | reply, edit, delete, react, unreact, pin, unpin |
interaction | commandName, options.get(name), customId, values, user, message, and the methods above |
rest | get, post, put, patch, delete for any other route |
| Events | ready, messageCreate, messageUpdate, messageDelete, interactionCreate, disconnect, resumed, reconnected, error, raw. Other gateway events use camelCase names, such as guildMemberAdd. |
The client sends heartbeats, resumes and reconnects by itself, and waits
before retrying a request answered with 429. Failed requests
throw GuildlyError with status and
code.
REST API
The address is https://guildly-api.octail.net. Send
Authorization: Bot <token>. Bodies are JSON, ids and
permission bitfields are decimal strings, and times are ISO 8601.
curl https://guildly-api.octail.net/channels/$CHANNEL_ID/messages \
-H "Authorization: Bot $GUILDLY_BOT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"content": "Raid starts in **15 minutes**."}' Routes open to bots
The usual permissions apply to each. Every other route answers 403 with {"error": "bots_not_allowed"}.
| Area | Routes |
|---|---|
| Yourself | GET /bot/me |
| Servers | GET /guildsGET /guilds/:id/channelsGET /guilds/:id/categoriesGET /guilds/:id/rolesGET /guilds/:id/membersGET /guilds/:id/members-with-rolesGET /guilds/:id/bots |
| People | GET /users/:idGET /users/:id/profileGET /guilds/:id/profiles |
| Messages | GET /channels/:id/messagesPOST /channels/:id/messagesPATCH /messages/:id (your own)DELETE /messages/:idPOST /channels/:id/typing |
| Reactions and pins | GET /channels/:id/messages/:messageId/reactionsPUT or DELETE /channels/:id/messages/:messageId/reactions/:emojiPOST /channels/:id/reactions (counts for many messages)GET /channels/:id/pinsPUT or DELETE /channels/:id/pins/:messageId |
| Threads | GET or POST /channels/:id/threadsGET or PATCH /threads/:id |
| Events | GET or POST /guilds/:id/eventsPATCH or DELETE /guilds/:id/events/:eventIdPUT or DELETE /guilds/:id/events/:eventId/interest |
| Invites | GET or POST /guilds/:id/invitesGET or DELETE /invites/:code |
| Files | POST /attachmentsGET /attachments/:id |
| Channels | POST /guilds/:id/channelsPATCH or DELETE /channels/:idPOST /guilds/:id/categoriesPATCH or DELETE /guilds/:id/categories/:categoryId |
| Roles | POST /guilds/:id/rolesPATCH or DELETE /guilds/:id/roles/:roleIdPUT or DELETE /guilds/:id/members/:userId/roles/:roleId |
| Moderation | PATCH /guilds/:id/members/:userId (nickname)DELETE /guilds/:id/members/:userId (kick)GET /guilds/:id/bansPUT or DELETE /guilds/:id/bans/:userId |
| Commands | GET or PUT /applications/@me/commandsGET or PUT /applications/@me/guilds/:guildId/commands |
GET /bot/me returns application,
user (id, username,
discriminator) and guilds (server ids).
Answering an interaction
These need no Authorization header: the interaction's token
in the address is the permission. Treat it as a secret.
| Request | Body |
|---|---|
POST /interactions/:id/:token/callback | {type, data?}, once, within 15 seconds. type is message (data: content, embeds, components, ephemeral), deferred (data: ephemeral), update or deferredUpdate (both for components only). A second callback gets 409, a late one 404. |
POST /interactions/:id/:token/followup | content, embeds, components, ephemeral; for 15 minutes |
PATCH /interactions/:id/:token/original | content, embeds, components; for 15 minutes |
curl https://guildly-api.octail.net/interactions/$INTERACTION_ID/$INTERACTION_TOKEN/callback \
-H "Content-Type: application/json" \
-d '{"type": "message", "data": {"content": "Pong!", "ephemeral": true}}' Messages you receive
Message objects may also carry embeds,
components, authorBot and, on answers to a
command, button or menu, interaction (id,
userId, userHandle, and
commandName for a command). Empty ones are left out.
Permission bits
A permission value is a sum of bits. Administrator includes all the others.
| Permission | Value |
|---|---|
| View channels | 1 |
| Send messages | 2 |
| Manage channels | 4 |
| Manage roles | 8 |
| Manage server | 16 |
| Administrator | 32 |
| Create invites | 64 |
| Manage messages | 128 |
| Kick members | 256 |
| Attach files | 512 |
| Join voice | 1024 |
| Mention everyone | 2048 |
| Change own nickname | 4096 |
| Manage nicknames | 8192 |
| Ban members | 16384 |
Older requests
POST /bot/messages with {channelId, content}
still posts a message, so earlier scripts keep working.
Gateway
The SDK handles this for you. To connect yourself, open a WebSocket to
wss://guildly-gw.octail.net. Frames are JSON with op,
d, and for events t and often a sequence number
s.
// 1. The gateway greets you.
{ "op": 10, "d": { "heartbeat_interval": 41250 } }
// 2. You identify, within 20 seconds.
{ "op": 2, "d": { "token": "Bot <token>" } }
// 3. You are ready. READY carries ids only.
{ "op": 0, "t": "READY", "d": {
"user": { "id": "<bot user id>" },
"application": { "id": "<application id>" },
"guilds": ["<server id>"],
"session_id": "<session id>" } }
// Every heartbeat_interval milliseconds, and the reply:
{ "op": 1 }
{ "op": 11 }
// After a dropped connection, instead of identifying:
{ "op": 6, "d": { "session_id": "<session id>", "last_seq": 42, "token": "Bot <token>" } } - Other events may arrive before
READY. - A successful resume replays frames after
last_seq, then sendsRESUMED. If you getINVALID_SESSION, identify on the same connection. - Resume only covers frames lost in flight, within about two minutes. Events published while you were disconnected are not replayed, so fetch what you need after reconnecting.
- A bot receives the events a member would, only for channels it can view. It gets no friend presence.
Events
INTERACTION_CREATE, MESSAGE_CREATE,
MESSAGE_UPDATE, MESSAGE_DELETE,
REACTION_ADD, REACTION_REMOVE,
TYPING_START, PRESENCE_UPDATE,
PROFILE_UPDATE, CHANNEL_PINS_UPDATE,
GUILD_CREATE, GUILD_UPDATE,
GUILD_DELETE, GUILD_MEMBER_ADD,
GUILD_MEMBER_UPDATE, GUILD_MEMBER_REMOVE,
GUILD_ROLE_CREATE, GUILD_ROLE_UPDATE,
GUILD_ROLE_DELETE, CHANNEL_CREATE,
CHANNEL_UPDATE, CHANNEL_DELETE,
CATEGORY_CREATE, CATEGORY_UPDATE,
CATEGORY_DELETE, THREAD_CREATE,
THREAD_UPDATE, GUILD_EVENT_CREATE,
GUILD_EVENT_UPDATE, GUILD_EVENT_DELETE and
GUILD_EVENT_INTEREST.
INTERACTION_CREATE looks like this. A button or menu has component (customId, type, and values for a menu) and message instead of command.
{
"id": "<interaction id>",
"token": "<interaction token>",
"applicationId": "<application id>",
"type": "command",
"guildId": "<server id>",
"channelId": "<channel id>",
"user": { "id": "<user id>", "username": "ada", "discriminator": "0042" },
"memberRoles": ["<role id>"],
"memberPermissions": "3",
"command": { "id": "<command id>", "name": "raid", "options": { "title": "Molten Core" } }
} Close codes
| Code | What to do |
|---|---|
| 1009, 4002 | A frame was too large or unreadable. Fix your code; do not retry in a loop. |
| 1012 | The server is restarting. Reconnect after a short, random delay. |
| 4003 | You did not identify in time. Reconnect. |
| 4004 | Authentication failed: a wrong or reset token, a deleted bot, or a suspended or banned bot or owner. Stop. |
| 4005, 4006 | The account is suspended, banned or gone. Stop. |
| 4008 | Too many connections or frames. Reconnect, waiting longer each time. |
Limits and errors
- A bot may make 50 requests a second. Over that, the reply is
429withretry-afterin seconds. - Spam protection also applies: sending many messages quickly, repeating the same text or mentioning many people is refused with
429. Your first answer to a command, button or menu is not counted for speed or repetition; follow-ups are. - Each person may use 5 commands, buttons or menus a second.
- One bot may hold 25 gateway connections. Inbound frames are limited to 16 KiB, and to bursts of 120 refilled at 2 a second.
- A muted owner stops the bot from posting, and a suspended or banned owner stops it altogether.
When you get a 429, wait for the time it gives. Do not retry at once.
The error in a failed reply is either a short code, sometimes with a detail saying what was wrong, or an object with code and message.
| Reply | What it means |
|---|---|
| 400 or 422 | Something in the request is missing or over a limit. |
| 401 | The token is missing or no longer works. |
| 403 | The bot lacks the permission, is not in that server, is muted through its owner, or the route is closed to bots. |
| 404 | No such thing, or an interaction that has expired. |
| 409 | The interaction was already answered, or a follow-up or edit came before the first answer. |
| 429 | Too many requests. See retry-after. |
Not supported
Guildly bots cannot yet use:
- voice channels
- direct messages
- interactions delivered to a web address (HTTP webhooks)
- pop-up forms (modals)
- autocomplete for command options
- commands in the menu of a user or a message
- gateway intents or sharding
Bots also have no access to friends, encryption keys, account settings, reports, read state, notification settings or GIF favourites. They cannot create, delete or transfer servers, or manage bots.