Guildly Open Guildly

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.

The token is shown only when you create the bot or reset it. Anyone who has it can act as your bot. Keep it in an environment variable and out of your source code. If it leaks, reset it in My bots: the old token stops working at once and its connections are closed.

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, channel and role.
  • string, integer and number options may offer up to 25 choices.

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 methodWhat 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, danger and link.
  • A link button takes an https url and no customId. It opens the address and sends your bot nothing.
  • Other buttons and menus take a customId of up to 100 characters, unique within the message.
  • Button and option labels are up to 80 and 100 characters. An option's value and description are up to 100.
  • A menu has 1 to 25 options, each with a different value. minValues (0 to 25) and maxValues (1 to 25) both default to 1. A placeholder is up to 150 characters.
  • Add disabled: true to 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(),
    },
  ],
});
PropertyLimit
Embeds in a message10, with at most 6,000 characters of text in all
title256 characters
description4,096 characters, formatted like a message
urlhttps; makes the title a link
colorA whole number from 0 to 0xFFFFFF
fields25; name 256 and value 1,024 characters; inline puts them in columns
footer.text2,048 characters
timestampAn ISO 8601 time with a time zone
imageUrl, thumbnailUrlA 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 }],
});
Anyone who has a file's link can open it.

SDK reference

MemberWhat 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.
channelssend(channelId, body), history(channelId, { limit, before }), typing(channelId)
commandsset(list, guildId?), list(guildId?)
attachmentsupload({ filename, contentType, data })
messagereply, edit, delete, react, unreact, pin, unpin
interactioncommandName, options.get(name), customId, values, user, message, and the methods above
restget, post, put, patch, delete for any other route
Eventsready, 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"}.

AreaRoutes
Yourself
GET /bot/me
Servers
GET /guilds
GET /guilds/:id/channels
GET /guilds/:id/categories
GET /guilds/:id/roles
GET /guilds/:id/members
GET /guilds/:id/members-with-roles
GET /guilds/:id/bots
People
GET /users/:id
GET /users/:id/profile
GET /guilds/:id/profiles
Messages
GET /channels/:id/messages
POST /channels/:id/messages
PATCH /messages/:id (your own)
DELETE /messages/:id
POST /channels/:id/typing
Reactions and pins
GET /channels/:id/messages/:messageId/reactions
PUT or DELETE /channels/:id/messages/:messageId/reactions/:emoji
POST /channels/:id/reactions (counts for many messages)
GET /channels/:id/pins
PUT or DELETE /channels/:id/pins/:messageId
Threads
GET or POST /channels/:id/threads
GET or PATCH /threads/:id
Events
GET or POST /guilds/:id/events
PATCH or DELETE /guilds/:id/events/:eventId
PUT or DELETE /guilds/:id/events/:eventId/interest
Invites
GET or POST /guilds/:id/invites
GET or DELETE /invites/:code
Files
POST /attachments
GET /attachments/:id
Channels
POST /guilds/:id/channels
PATCH or DELETE /channels/:id
POST /guilds/:id/categories
PATCH or DELETE /guilds/:id/categories/:categoryId
Roles
POST /guilds/:id/roles
PATCH or DELETE /guilds/:id/roles/:roleId
PUT or DELETE /guilds/:id/members/:userId/roles/:roleId
Moderation
PATCH /guilds/:id/members/:userId (nickname)
DELETE /guilds/:id/members/:userId (kick)
GET /guilds/:id/bans
PUT or DELETE /guilds/:id/bans/:userId
Commands
GET or PUT /applications/@me/commands
GET 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.

RequestBody
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/followupcontent, embeds, components, ephemeral; for 15 minutes
PATCH /interactions/:id/:token/originalcontent, 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.

PermissionValue
View channels1
Send messages2
Manage channels4
Manage roles8
Manage server16
Administrator32
Create invites64
Manage messages128
Kick members256
Attach files512
Join voice1024
Mention everyone2048
Change own nickname4096
Manage nicknames8192
Ban members16384

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 sends RESUMED. If you get INVALID_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

CodeWhat to do
1009, 4002A frame was too large or unreadable. Fix your code; do not retry in a loop.
1012The server is restarting. Reconnect after a short, random delay.
4003You did not identify in time. Reconnect.
4004Authentication failed: a wrong or reset token, a deleted bot, or a suspended or banned bot or owner. Stop.
4005, 4006The account is suspended, banned or gone. Stop.
4008Too 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 429 with retry-after in 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.

ReplyWhat it means
400 or 422Something in the request is missing or over a limit.
401The token is missing or no longer works.
403The bot lacks the permission, is not in that server, is muted through its owner, or the route is closed to bots.
404No such thing, or an interaction that has expired.
409The interaction was already answered, or a follow-up or edit came before the first answer.
429Too 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.