# vexel.js: everything in one page

vexel.js is the official JavaScript library for making **bots on Vexel** (a chat, voice and community app). It runs on Node.js and works a lot like discord.js. This page has everything you need to build a working bot: how to install it, a complete bot you can copy, the rules that trip people up, and a cheat sheet. It's written so you can also hand it to an AI assistant.

> **For AI assistants:** use only the names on this page. vexel.js is not discord.js. Most discord.js v14 code runs unchanged, but the differences are listed under [Coming from discord.js](#coming-from-discordjs). Don't install or import `discord.js`, `@discordjs/rest`, `@discordjs/voice` or `@discordjs/builders`; everything comes from `vexel.js`.

## 1. Install

vexel.js is **not on the npm registry**. `npm install vexel.js` fails with a 404. Install it from the Vexel website:

```bash
mkdir my-bot
cd my-bot
npm init -y
npm install https://vexel.pulsedmc.net/sdk/vexel.js.tgz
```

You need **Node.js 18.17 or newer** (`node --version` to check). This is the only package you need. Music bots also need `npm install werift opusscript` and [ffmpeg](https://ffmpeg.org).

## 2. Set up the bot in Vexel

1. Open Vexel and go to **Home → Developers** (the Developer Portal). Choose **New application** and give it a name.
2. Open the **Bot** tab and copy the **token**. It's shown only once; if you lose it, press **Reset token**.
3. Still in the **Bot** tab, turn on **Message Content** if your bot reads what people type (like `!ping`). Slash commands don't need it.
4. Open the **Invite link** tab, pick permissions (at least **Send Messages**), and open the link to add the bot to your server. You need **Manage Server** in that server.

## 3. Your first bot (copy this)

Create these three files in `my-bot`.

**`.env`** (your token; never share this file or put it on GitHub):

```bash
VEXEL_TOKEN=paste-your-bot-token-here
```

**`bot.js`**:

```js
const { Client, GatewayIntentBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('vexel.js');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,          // servers, channels and roles (almost every bot needs this)
    GatewayIntentBits.GuildMessages,   // messages in servers
    GatewayIntentBits.MessageContent,  // the text of those messages (turn on "Message Content" in the Bot tab)
  ],
});

// Runs once when the bot is connected.
client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}`);
});

// A text command: someone types !ping, the bot answers.
client.on('messageCreate', async (message) => {
  if (message.author.bot) return; // ignore other bots (and ourselves)
  if (message.content === '!ping') {
    await message.reply('Pong!');
  }
});

// A slash command: /hello. vexel.js uploads it to Vexel for you when the bot starts.
client.commands.register({
  name: 'hello',
  description: 'Say hello',
  options: [{ name: 'name', description: 'Who to greet', type: 'string', required: false }],
  execute: async (interaction) => {
    const name = interaction.options.getString('name') ?? interaction.user.username;
    const embed = new EmbedBuilder().setTitle(`Hello, ${name}!`).setColor('#F5C518');
    const row = new ActionRowBuilder().addComponents(
      new ButtonBuilder().setCustomId('wave').setLabel('Wave back').setStyle(ButtonStyle.Primary),
    );
    await interaction.reply({ embeds: [embed], components: [row] });
  },
});

// What happens when someone clicks the button with customId 'wave'.
client.components.onButton('wave', async (interaction) => {
  await interaction.reply({ content: `👋 ${interaction.user.username} waved back!` });
});

// Always handle errors, or Node.js stops the bot when one happens.
client.on('error', (error) => console.error(error));

client.login(process.env.VEXEL_TOKEN);
```

**Run it** (Node 20.6+ reads the `.env` file with `--env-file`):

```bash
node --env-file=.env bot.js
```

On Node 18, run `npm install dotenv` and add `require('dotenv').config();` as the first line of `bot.js`, then `node bot.js`. Or set the variable yourself: `VEXEL_TOKEN=... node bot.js` (macOS/Linux) or `set VEXEL_TOKEN=...` then `node bot.js` (Windows).

You should see `Logged in as …`. In your server, type `!ping` and use `/hello`.

**Using `import` instead of `require`:** both work. With `"type": "module"` in `package.json` (or a `.mjs` file), write `import { Client, GatewayIntentBits } from 'vexel.js';`.

## 4. Rules that trip people up

1. **Reply to every slash command, button, select menu and modal within 3 seconds.** If the work takes longer, call `await interaction.deferReply()` first, then `await interaction.editReply(...)` when you're done (you then have 15 minutes).
2. **Reading message text needs the `MessageContent` intent** in code *and* the **Message Content** switch in the Developer Portal. Without it, `message.content` is empty for other people's messages. If the switch is off, `login()` fails with error code `GATEWAY_4014`. `GuildMembers` and `GuildPresences` work the same way (**Server Members** and **Presence** switches).
3. **Don't register commands with REST yourself.** `client.commands.register({...})` uploads commands when the bot starts and runs the right `execute`. (The discord.js `REST` + `Routes` way also works; see below.)
4. **Option types are lowercase strings:** `'string'`, `'integer'`, `'number'`, `'boolean'`, `'user'`, `'channel'`, `'role'`, `'mentionable'`, `'attachment'`, `'subcommand'`, `'subcommandGroup'`. Required options must come before optional ones. Command names are lowercase, 1–32 characters, no spaces.
5. **Buttons and menus are matched by `customId`** with `client.components.onButton(id, handler)`, `onSelect` and `onModal`. A string ending in `:` matches as a prefix (`'vote:'` matches `'vote:yes'`); a RegExp works too.
6. **Answer only once.** Use `reply()` *or* `deferReply()` first, then `editReply()` / `followUp()`. Replying twice throws `INTERACTION_ALREADY_REPLIED`. To change the message a button is on, use `interaction.update({...})` instead of `reply`.
7. **Private replies:** `interaction.reply({ content: 'Only you can see this', ephemeral: true })`. (`flags: MessageFlags.Ephemeral` works too.)
8. **Permissions are checked by Vexel.** The bot can only act on members whose highest role is *below* the bot's highest role. If something is refused you get a `VexelAPIError` with `code === 50013`.
9. **A bot's first DM to someone arrives as a message request.** They only see it if they accept. Don't rely on DMs.
10. **Always add `client.on('error', console.error)`.**
11. **The token comes from the environment.** `client.login()` with no argument reads `VEXEL_TOKEN`. Never put the token in your code.
12. **Threads, scheduled events, invites, audit logs, AutoMod rules, polls and webhooks are supported** with the same calls as discord.js (`channel.threads.create()`, `guild.scheduledEvents.create()`, `channel.createInvite()`, `guild.fetchAuditLogs()`, `channel.send({ poll })`). Not available: receiving voice audio, stage channels, private threads, creating emoji through the API.

## 5. Cheat sheet

**Client**

```js
new Client({ intents: [...] })            // required: intents
client.login(token?)                      // token defaults to process.env.VEXEL_TOKEN
client.on('ready' | 'messageCreate' | 'interactionCreate' | 'guildMemberAdd' | 'error' | ..., handler)
client.user                               // the bot: .id, .username, .setActivity(), .setStatus()
client.guilds.cache / client.channels.cache / client.users.cache   // Collections (a Map with .find, .filter, .map, .first ...)
await client.channels.fetch(id) / client.users.fetch(id) / client.guilds.fetch(id)
client.destroy()
```

**Messages** (`message` from `messageCreate`, or `channel.send` result)

```js
message.content, message.author (User), message.member (GuildMember), message.channel, message.guild
await message.reply('text' | { content, embeds, components, files })
await message.channel.send('text' | { ... })
await message.edit({ content }); await message.delete(); await message.react('👍');
await channel.messages.fetch({ limit: 50 }); await channel.bulkDelete(20);
```

**Slash commands**

```js
client.commands.register({
  name: 'kick', description: 'Kick someone',
  defaultMemberPermissions: 'KickMembers',          // hide from people without this permission
  guildId: '123',                                   // optional: only in one server (updates instantly; good for testing)
  options: [{ name: 'user', description: 'Who', type: 'user', required: true },
            { name: 'reason', description: 'Why', type: 'string', choices: [{ name: 'Spam', value: 'spam' }] }],
  execute: async (interaction) => { /* must reply within 3 seconds */ },
  autocomplete: async (interaction) => interaction.respond([{ name: 'Option', value: 'option' }]),
});
interaction.options.getString('name') / getInteger / getNumber / getBoolean / getUser / getMember / getChannel / getRole / getAttachment
interaction.options.getSubcommand()
interaction.user, interaction.member, interaction.guild, interaction.channel, interaction.commandName
```

**Responding to any interaction** (commands, buttons, menus, modals)

```js
await interaction.reply({ content, embeds, components, ephemeral: true })
await interaction.deferReply({ ephemeral: true });  await interaction.editReply({ content })
await interaction.followUp({ content, ephemeral: true })
await interaction.update({ content, components })   // buttons/menus: edit the message they're on
await interaction.showModal(modal)                  // open a form (must be the first response)
```

**Buttons, menus, modals**

```js
new ActionRowBuilder().addComponents(new ButtonBuilder().setCustomId('id').setLabel('Click').setStyle(ButtonStyle.Primary))
new ButtonBuilder().setLabel('Website').setStyle(ButtonStyle.Link).setURL('https://example.com')   // link buttons have no customId
new StringSelectMenuBuilder().setCustomId('pick').addOptions({ label: 'A', value: 'a' }, { label: 'B', value: 'b' })
new ModalBuilder().setCustomId('form').setTitle('Title').addComponents(new TextInputBuilder().setCustomId('text').setLabel('Your answer'))
client.components.onButton('id', (i) => ...); client.components.onSelect('pick', (i) => i.values[0]); client.components.onModal('form', (i) => i.fields.getTextInputValue('text'))
```

Up to 5 rows per message; a row holds up to 5 buttons or 1 select menu. Button styles: `Primary`, `Secondary`, `Success`, `Danger`, `Link`.

**Embeds:** `new EmbedBuilder().setTitle().setDescription().setColor('#hex').addFields({ name, value, inline }).setFooter({ text }).setTimestamp()`. A plain object `{ title, description, color }` works too.

**Members and moderation**

```js
const member = await interaction.guild.members.fetch(userId);
await member.kick('reason'); await member.ban({ reason }); await member.timeout(10 * 60_000, 'reason');
await member.roles.add(roleId); await member.roles.remove(roleId); member.roles.cache.has(roleId);
member.permissions.has('ManageMessages'); member.kickable; member.bannable;
await interaction.guild.members.ban(userId, { reason, deleteMessageSeconds: 3600 });
```

**Intents:** `Guilds`, `GuildMembers`\*, `GuildModeration`, `GuildVoiceStates`, `GuildPresences`\*, `GuildMessages`, `GuildMessageReactions`, `GuildMessageTyping`, `DirectMessages`, `DirectMessageReactions`, `DirectMessageTyping`, `MessageContent`\* (\* = also turn on in the Developer Portal). `UPPER_SNAKE` names like `GUILD_MESSAGES` work too, but use one style.

**Permissions:** PascalCase strings like `'SendMessages'`, `'ManageMessages'`, `'KickMembers'`, `'BanMembers'`, `'ModerateMembers'`, `'ManageRoles'`, `'Administrator'`, or `PermissionFlagsBits.X`.

**Errors:** `VexelAPIError` (`.status`, `.code`, `.message`) when Vexel refuses a request; `VexelError` (`.code` such as `INTERACTION_EXPIRED`) for vexel.js problems. All are exported from `vexel.js`.

## 6. Splitting a bigger bot into files

```
my-bot/
  .env
  package.json
  index.js          // creates the client and loads the commands
  commands/
    ping.js
    kick.js
```

**`commands/ping.js`**

```js
module.exports = {
  name: 'ping',
  description: 'Check that the bot is alive',
  execute: (interaction) => interaction.reply(`Pong! ${interaction.client.ping} ms`),
};
```

**`index.js`**

```js
const fs = require('node:fs');
const path = require('node:path');
const { Client, GatewayIntentBits } = require('vexel.js');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });
for (const file of fs.readdirSync(path.join(__dirname, 'commands')).filter((f) => f.endsWith('.js'))) {
  client.commands.register(require(path.join(__dirname, 'commands', file)));
}
client.on('ready', () => console.log(`Ready as ${client.user.username}`));
client.on('error', console.error);
client.login(); // reads VEXEL_TOKEN
```

## 7. Coming from discord.js

Most discord.js v14 code runs on vexel.js as it is. Change the import from `'discord.js'` to `'vexel.js'` and it usually just works.

| You write | On vexel.js |
|---|---|
| `require('discord.js')` / `import ... from 'discord.js'` | `require('vexel.js')` / `import ... from 'vexel.js'` |
| `npm install discord.js` | `npm install https://vexel.pulsedmc.net/sdk/vexel.js.tgz` |
| `Events.ClientReady`, `'clientReady'`, `'ready'` | all work |
| `GatewayIntentBits.Guilds`, `IntentsBitField.Flags.Guilds` | both work |
| `partials: [Partials.Channel]` | accepted and ignored (not needed) |
| `new REST().setToken(t)` + `rest.put(Routes.applicationCommands(id), { body })` | works; or use `client.commands.register()`, which is simpler |
| `client.on('interactionCreate', ...)` + `interaction.isChatInputCommand()` | works; or use `execute` in `client.commands.register()` |
| `ephemeral: true` / `flags: MessageFlags.Ephemeral` | both work |
| `@discordjs/voice` (`joinVoiceChannel`) | built in: `client.voice.join(channel)` with `createAudioPlayer()` / `createAudioResource()` from `vexel.js` (see the guide) |
| Threads, scheduled events, invites, audit logs, AutoMod, polls, sharding | work the same way |
| Receiving voice audio, stage channels, private threads | not on Vexel |
| Discord IDs and `discord.com` links | Vexel has its own IDs. Get them in code (`message.guild.id`, `interaction.channelId`, `role.id`); messages also have **Copy Message ID** in their menu |

## 8. Common problems

| Problem | Fix |
|---|---|
| `npm install vexel.js` → 404 | Install from the website: `npm install https://vexel.pulsedmc.net/sdk/vexel.js.tgz` |
| `Cannot find module 'vexel.js'` | Run the install command inside your bot's folder (the one with `package.json`) |
| Bot starts but `message.content` is empty | Add `GatewayIntentBits.MessageContent` *and* turn on **Message Content** in the Bot tab |
| `login()` fails with `GATEWAY_4014` | You asked for a privileged intent that's switched off in the Bot tab |
| `login()` fails with `GATEWAY_4004` | Wrong token, or it was reset. Copy a new one from the Bot tab |
| `VEXEL_TOKEN` is undefined | The `.env` file isn't being read: run `node --env-file=.env bot.js`, or use `dotenv` (see step 3) |
| Slash command doesn't show up | Wait a few seconds after the bot starts, then reopen the channel. Use `guildId` while testing. Check the bot was invited to that server |
| "The application did not respond" / `INTERACTION_EXPIRED` | Reply within 3 seconds, or `deferReply()` first |
| `INTERACTION_ALREADY_REPLIED` | Use `editReply()` or `followUp()` after the first reply |
| `VexelAPIError` code `50013` | Missing permissions, or the target's role is above the bot's role |
| `VexelAPIError` code `50007` | That person doesn't accept DMs from the bot |
| Bot crashes on an error | Add `client.on('error', console.error)` |

## More

- The full **guide** and **API reference** follow below on this page (and are in `docs/guide.md` and `docs/api.md` in the package).
- Examples are in the package's `examples/` folder: a ping bot, slash commands, moderation, buttons, modals and a music bot.


---

# vexel.js guide

This guide goes from an empty folder to a bot with slash commands, buttons, modals, moderation and music. Each section stands on its own, so you can jump to what you need.

- [Installation](#installation)
- [Creating a bot application](#creating-a-bot-application)
- [Getting and protecting the token](#getting-and-protecting-the-token)
- [Inviting the bot to a server](#inviting-the-bot-to-a-server)
- [Permissions](#permissions)
- [Gateway intents](#gateway-intents)
- [Events](#events)
- [Sending messages](#sending-messages)
- [Embeds](#embeds)
- [Slash commands](#slash-commands)
- [Interactions: replying, deferring, follow-ups](#interactions)
- [Buttons and select menus](#buttons-and-select-menus)
- [Modals](#modals)
- [Autocomplete](#autocomplete)
- [User and message commands](#user-and-message-commands)
- [Moderation](#moderation)
- [Members and roles](#members-and-roles)
- [Channels](#channels)
- [Direct messages](#direct-messages)
- [Threads and scheduled events](#threads-and-scheduled-events)
- [Invites, audit log, AutoMod, polls and webhooks](#invites-audit-log-automod-polls-and-webhooks)
- [Log in with Vexel (OAuth2)](#log-in-with-vexel-oauth2)
- [Sharding](#sharding)
- [Voice and music bots](#voice-and-music-bots)
- [Presence and profile](#presence-and-profile)
- [Reconnecting and resuming](#reconnecting-and-resuming)
- [Rate limits](#rate-limits)
- [Errors](#errors)
- [Using another API address](#using-another-api-address)

---

## Installation

```bash
mkdir my-bot && cd my-bot
npm init -y
npm install https://vexel.pulsedmc.net/sdk/vexel.js.tgz
```

vexel.js isn't on the npm registry, so `npm install vexel.js` fails; use the link above. You need Node.js 18.17 or newer. TypeScript users get typings automatically; nothing else to install. Both `require('vexel.js')` and `import { Client } from 'vexel.js'` work.

For a complete first bot, the rules that trip people up and a cheat sheet, start with [Everything on one page](ai.md).

## Creating a bot application

1. In Vexel, open **Home → Developers** (the Developer Portal).
2. Choose **New application**, give it a name and pick **vexel.js** as the library.
3. Every application has a bot user with the same name. Change its picture and description in the **General** tab.

## Getting and protecting the token

The **Bot** tab shows the token once when you create or reset it. Treat it like a password:

- Store it in an environment variable (`VEXEL_TOKEN`) or a secrets manager, never in your code or a public repository. `client.login()` reads `VEXEL_TOKEN` when you don't pass a token.
- Vexel stores only a hash of the token, so nobody (including Vexel staff) can show it to you again.
- If it leaks, press **Reset token**. The old token stops working immediately, and any connected or resumable gateway sessions using it are closed.

## Inviting the bot to a server

Use the **Invite link** tab to choose permissions and copy the link. Or generate one in code:

```js
console.log(client.generateInvite({ permissions: ['SendMessages', 'EmbedLinks', 'ManageMessages'] }));
```

The person adding the bot needs **Manage Server**, and can only grant permissions they have themselves. The bot gets its own role with those permissions, placed where server admins can move it.

## Permissions

Vexel checks every action on the server: the bot's role permissions, channel overwrites, and the **role hierarchy**. A bot can only act on members whose highest role is below the bot's highest role, and can only manage roles below its own. When a check fails you get a `VexelAPIError` with `code === 50013` (Missing Permissions).

Use `PermissionsBitField` to check ahead and give friendly messages:

```js
const { PermissionFlagsBits } = require('vexel.js');

if (!interaction.memberPermissions.has(PermissionFlagsBits.BanMembers)) { /* … */ }
if (!channel.permissionsFor(client.user.id).has(['ViewChannel', 'SendMessages'])) { /* … */ }
if (!member.bannable) { /* their highest role is above the bot's */ }
```

Permission names follow the PascalCase list in `PermissionFlagsBits`: `SendMessages`, `ManageRoles`, `ModerateMembers` and so on. `UPPER_SNAKE` names such as `MANAGE_ROLES` work too.

## Gateway intents

Intents choose which events your bot receives. Ask only for what you need:

| Intent | Events |
|---|---|
| `Guilds` | servers, channels, roles, pins |
| `GuildMembers` (privileged) | member join, leave and update, `members.fetch()` for all members |
| `GuildModeration` | accepted (moderation actions arrive as member events) |
| `GuildVoiceStates` | voice states; **required for voice** |
| `GuildPresences` (privileged) | presence updates |
| `GuildMessages` | messages in servers |
| `GuildMessageReactions` | reactions in servers |
| `GuildMessageTyping` | typing in servers |
| `DirectMessages`, `DirectMessageReactions`, `DirectMessageTyping` | the same in DMs |
| `MessageContent` (privileged) | message text, embeds and attachments in servers (without it you only see your own messages and ones that mention the bot) |
| `GuildScheduledEvents` | scheduled events and who is interested |
| `GuildModeration` | bans and audit log entries |
| `GuildInvites`, `GuildWebhooks` | invite and webhook changes |
| `AutoModerationExecution` | AutoMod blocks (needs Manage Server) |
| `GuildMessagePolls`, `DirectMessagePolls` | poll votes |

Privileged intents must be switched on in the Developer Portal's **Bot** tab. If they aren't, `login()` rejects with an error whose code is `GATEWAY_4014` and whose message explains what to change. The server enforces intents: events you didn't ask for are never sent.

```js
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
```

## Events

```js
client.on('ready', (c) => console.log(`Ready as ${c.user.username} in ${c.guilds.cache.size} servers`));
client.on('messageCreate', (message) => {});
client.on('interactionCreate', (interaction) => {});
client.on('guildMemberAdd', (member) => {});
```

| Event | Arguments |
|---|---|
| `ready` | client |
| `resumed`, `shardDisconnect`, `shardReconnecting`, `invalidated` | connection details |
| `guildCreate`, `guildAvailable`, `guildUpdate` (old, new), `guildDelete` | guild |
| `messageCreate`, `messageUpdate` (old, new), `messageDelete`, `messageDeleteBulk` (messages, channel) | message(s) |
| `messageReactionAdd`, `messageReactionRemove` (reaction, user, details), `messageReactionRemoveAll`, `messageReactionRemoveEmoji` | reaction data |
| `typingStart` | `{ channel, user, member, guild }` |
| `guildMemberAdd`, `guildMemberRemove`, `guildMemberUpdate` (old, new), `guildMembersChunk` | member(s) |
| `roleCreate`, `roleUpdate` (old, new), `roleDelete` | role |
| `channelCreate`, `channelUpdate` (old, new), `channelDelete`, `channelPinsUpdate` (channel, time) | channel |
| `voiceStateUpdate` (old, new), `presenceUpdate` (old, new) | state |
| `interactionCreate` | interaction |
| `rateLimited`, `debug`, `error`, `raw` | diagnostics |

Each of these comes from a gateway event: `GUILD_CREATE`, `MESSAGE_CREATE`, `MESSAGE_DELETE_BULK`, `MESSAGE_REACTION_REMOVE_ALL`, `GUILD_ROLE_CREATE`, `CHANNEL_PINS_UPDATE`, `VOICE_STATE_UPDATE` and so on. Listen to `raw` to see the raw gateway packets.

Always listen to `error`. Without a listener, Node.js crashes on an emitted error.

## Sending messages

```js
await channel.send('Plain text');
await channel.send({ content: 'With options', allowedMentions: { parse: [] } }); // no pings
await message.reply('Replying');                       // shows the "replying to" preview
await message.reply({ content: 'Quiet reply', allowedMentions: { repliedUser: false } });
await channel.send({ files: ['./chart.png', { attachment: buffer, name: 'data.csv' }] });
await message.edit({ content: 'Edited' });
await message.delete();
await message.react('👍');                             // or '<:name:id>' for a server emoji
await message.pin(); await message.unpin();
await channel.sendTyping();
```

History and paging:

```js
const one = await channel.messages.fetch('123');
const recent = await channel.messages.fetch({ limit: 50 });            // newest first
const older = await channel.messages.fetch({ limit: 100, before: recent.last().id });
for await (const m of channel.messages.iterate({ max: 500 })) { /* walks back through history */ }
const pins = await channel.messages.fetchPinned();
await channel.bulkDelete(20);                                          // or an array of messages / IDs (max 100)
```

Mentions: `${user}` becomes `<@id>`; also `userMention(id)`, `roleMention(id)`, `channelMention(id)`. Formatting helpers: `bold`, `italic`, `codeBlock`, `inlineCode`, `hyperlink`, `time(date, 'R')`, `escapeMarkdown`.

Messages are limited to 2000 characters. `splitMessage(longText)` breaks text into pieces that fit.

## Embeds

```js
const { EmbedBuilder } = require('vexel.js');

const embed = new EmbedBuilder()
  .setTitle('Server stats')
  .setDescription('Updated every hour')
  .setColor('#F5C518')
  .addFields({ name: 'Members', value: '128', inline: true }, { name: 'Online', value: '42', inline: true })
  .setThumbnail(guild.iconURL())
  .setFooter({ text: 'vexel.js' })
  .setTimestamp();
await channel.send({ embeds: [embed] });
```

Plain objects work too: `{ title, description, color: '#5865F2', fields: [...] }`. Colors can be `'#hex'`, a number, `[r, g, b]` or a name from `Colors`.

## Slash commands

Register commands with their handlers. vexel.js uploads them when the bot logs in (and again a moment after you register more), then calls the right handler:

```js
client.commands.register({
  name: 'weather',                // lowercase, 1-32 characters
  description: 'Get the weather',
  options: [
    { name: 'city', description: 'Which city', type: 'string', required: true, maxLength: 60 },
    { name: 'units', description: 'Units', type: 'string', choices: [{ name: 'Celsius', value: 'c' }, { name: 'Fahrenheit', value: 'f' }] },
    { name: 'days', description: 'Forecast days', type: 'integer', minValue: 1, maxValue: 7 },
  ],
  execute: async (interaction) => {
    const city = interaction.options.getString('city');
    const units = interaction.options.getString('units') ?? 'c';
    await interaction.reply(`Weather for ${city} in °${units.toUpperCase()}…`);
  },
});
```

Option types are `string`, `integer`, `number`, `boolean`, `user`, `channel`, `role`, `mentionable`, `attachment`, `subcommand` and `subcommandGroup`. Required options must come before optional ones, and vexel.js tells you at startup if they don't.

Read the values with `getString`, `getInteger`, `getNumber`, `getBoolean`, `getUser`, `getMember`, `getChannel`, `getRole`, `getMentionable` and `getAttachment`. Pass `true` as the second argument to require a value.

**Subcommands:**

```js
client.commands.register({
  name: 'config', description: 'Bot settings',
  options: [
    { name: 'show', description: 'Show settings', type: 'subcommand' },
    { name: 'set', description: 'Change a setting', type: 'subcommand', options: [{ name: 'key', description: 'Setting', type: 'string', required: true }, { name: 'value', description: 'Value', type: 'string', required: true }] },
  ],
  subcommands: {
    show: (i) => i.reply({ content: '…', ephemeral: true }),
    set: (i) => i.reply({ content: `Set ${i.options.getString('key')}`, ephemeral: true }),
  },
});
```

For subcommand groups, key the handler as `'group sub'`, or use a single `execute` and branch on `getSubcommandGroup()` and `getSubcommand()`.

**Permissions:** `defaultMemberPermissions: 'ManageMessages'` hides the command from members without that permission. `dmPermission: false` keeps it out of DMs.

**Server-only commands:** add `guildId: '123'`. These are handy while developing.

**Managing registration yourself:** set `new Client({ commands: { sync: false } })`, then use `client.application.commands.set([...])`, `.create()`, `.edit()`, `.delete()` and `.fetch()`. Use `guild.commands` for a single server. `SlashCommandBuilder` is available if you prefer builders.

If a handler throws, vexel.js emits `error` and sends the person an ephemeral "Something went wrong" message, so they're never left waiting.

## Interactions

Every command, button, select menu and modal is an interaction, and it must get a **first response within 3 seconds**:

| Method | Use |
|---|---|
| `reply(options)` | send a message; `ephemeral: true` shows it only to that person |
| `deferReply({ ephemeral })` | shows "thinking…"; you then have 15 minutes |
| `editReply(options)` | change the reply or finish a deferred one |
| `followUp(options)` | send more messages (they can be ephemeral) |
| `deleteReply()`, `fetchReply()` | manage the original reply |
| `update(options)` / `deferUpdate()` | components and modals: edit the message the button is on |
| `showModal(modal)` | open a form (must be the first response) |

If you respond too late, vexel.js throws `INTERACTION_EXPIRED` with a hint to defer. `interaction.responseTimeLeft` tells you how many milliseconds are left. Responding twice throws `INTERACTION_ALREADY_REPLIED`.

```js
client.on('interactionCreate', async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== 'report') return;
  await interaction.deferReply({ ephemeral: true });
  const result = await buildReport();          // can take minutes
  await interaction.editReply({ content: result });
  await interaction.followUp({ content: 'Additional information', ephemeral: true });
});
```

To check what kind of interaction you have, use `isChatInputCommand()`, `isUserContextMenuCommand()`, `isMessageContextMenuCommand()`, `isButton()`, `isStringSelectMenu()`, `isUserSelectMenu()`, `isRoleSelectMenu()`, `isChannelSelectMenu()`, `isMentionableSelectMenu()`, `isModalSubmit()` and `isAutocomplete()`.

## Buttons and select menus

```js
const { ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, UserSelectMenuBuilder, RoleSelectMenuBuilder, ChannelSelectMenuBuilder, ChannelType } = require('vexel.js');

await interaction.reply({
  content: 'Choose:',
  components: [
    new ActionRowBuilder().addComponents(
      new ButtonBuilder().setCustomId('ok').setLabel('OK').setStyle(ButtonStyle.Success),
      new ButtonBuilder().setLabel('Docs').setStyle(ButtonStyle.Link).setURL('https://example.com'),
    ),
    new ActionRowBuilder().addComponents(new StringSelectMenuBuilder().setCustomId('color').setPlaceholder('Color').addOptions({ label: 'Gold', value: 'gold' }, { label: 'Blue', value: 'blue' })),
    new ActionRowBuilder().addComponents(new UserSelectMenuBuilder().setCustomId('people').setMaxValues(3)),
    new ActionRowBuilder().addComponents(new ChannelSelectMenuBuilder().setCustomId('where').setChannelTypes(ChannelType.GuildText)),
  ],
});
```

A message can have up to 5 rows. A row holds up to 5 buttons or 1 select menu.

Route component interactions by `customId`:

```js
client.components.onButton('ok', (i) => i.update({ content: 'Confirmed!', components: [] }));
client.components.onButton('vote:', (i, [, choice]) => i.reply(`You voted ${choice}`));   // prefix match: 'vote:yes'
client.components.onButton(/^page:(\d+)$/, (i, [, page]) => showPage(i, Number(page)));    // regex
client.components.onSelect('color', (i) => i.reply(`Picked ${i.values[0]}`));
client.components.onSelect('people', (i) => i.reply(i.users.map((u) => u.username).join(', ')));
```

User and role select menus give you `i.users`, `i.members`, `i.roles` and `i.channels`, each a Collection. Vexel only lets people pick users, roles and channels they can see in that server. It also checks string select values against your options.

You can also wait for a click inline: `const click = await message.awaitMessageComponent({ filter: (i) => i.user.id === author.id, time: 30_000 })`.

## Modals

```js
const { ModalBuilder, TextInputBuilder, TextInputStyle } = require('vexel.js');

await interaction.showModal(new ModalBuilder()
  .setCustomId('feedback')
  .setTitle('Feedback')
  .addComponents(
    new TextInputBuilder().setCustomId('subject').setLabel('Subject').setMaxLength(80),
    new TextInputBuilder().setCustomId('details').setLabel('Details').setStyle(TextInputStyle.Paragraph).setMinLength(10),
  ));

client.components.onModal('feedback', (i) => i.reply({ content: `Got: ${i.fields.getTextInputValue('subject')}`, ephemeral: true }));
```

A modal can have up to 5 text inputs. Vexel checks required inputs and length limits before your bot sees the submission. Each modal can be submitted once, and it expires after 15 minutes. To wait inline, use `await interaction.awaitModalSubmit({ filter, time })`.

You can show a modal from a command or a component, but not after you've already replied or deferred.

## Autocomplete

```js
client.commands.register({
  name: 'tag', description: 'Show a tag',
  options: [{ name: 'name', description: 'Tag name', type: 'string', required: true, autocomplete: true }],
  autocomplete: async (interaction) => {
    const typed = interaction.options.getFocused();
    await interaction.respond(tags.filter((t) => t.startsWith(typed)).slice(0, 25).map((t) => ({ name: t, value: t })));
  },
  execute: (interaction) => interaction.reply(getTag(interaction.options.getString('name'))),
});
```

Autocomplete works on `string`, `integer` and `number` options that don't have fixed `choices`. Respond within about 2.5 seconds with up to 25 suggestions. Values typed during autocomplete aren't validated yet, so check them again in `execute`.

## User and message commands

These appear in the **Apps** menu when someone right-clicks a person or a message:

```js
client.commands.register(
  { type: 'user', name: 'High five', execute: (i) => i.reply(`🙌 ${i.targetUser}`) },
  { type: 'message', name: 'Translate', execute: (i) => i.reply({ content: translate(i.targetMessage.content), ephemeral: true }) },
);
```

User and message commands have no description or options, and their names may include spaces and capital letters.

## Moderation

```js
await member.kick('Spamming');
await guild.members.ban(userId, { reason: 'Raid', deleteMessageSeconds: 3600 });  // also removes their last hour of messages (max 7 days)
await guild.members.unban(userId);
await member.timeout(10 * 60_000, 'Cool down');   // null ends it; max 28 days
await member.setNickname('Renamed', 'Inappropriate name');
const bans = await guild.bans.fetch();
```

Reasons appear in the server's audit log. Bot moderation actions are always logged with the bot as the moderator.

`member.kickable`, `bannable`, `moderatable` and `manageable` tell you ahead of time whether the role hierarchy allows the action. The server enforces the same rules regardless. The server owner can never be kicked, banned or timed out.

## Members and roles

```js
const member = await guild.members.fetch('123');               // one member
const everyone = await guild.members.fetch();                  // all members (GuildMembers intent)
const matches = await guild.members.fetch({ query: 'sam', limit: 10 }); // name prefix, over the gateway
const some = await guild.members.fetch({ user: ['1', '2'] });
const found = await guild.members.search({ query: 'sam' });    // over REST

await member.roles.add(role); await member.roles.remove(role); member.roles.has(roleId);
member.roles.highest; member.permissions.has('ManageMessages'); member.displayName;

const role = await guild.roles.create({ name: 'Helpers', color: '#57F287', permissions: ['ManageMessages'], mentionable: true });
await role.edit({ name: 'Helpers+', hoist: true });
await role.setPermissions(['ManageMessages', 'MuteMembers']);
await role.delete();
```

A bot can only create roles below its own highest role, and can only grant permissions it has itself.

## Channels

```js
const ch = await guild.channels.create({ name: 'announcements', type: 'text', topic: 'News', permissionOverwrites: [
  { id: guild.id, deny: ['SendMessages'] },          // @everyone can read but not post
  { id: modRoleId, allow: ['SendMessages'] },
] });
await ch.edit({ topic: 'Updated topic', rateLimitPerUser: 10 });   // 10s slowmode
await ch.permissionOverwrites.edit(member, { SendMessages: false });  // true allow, false deny, null inherit
await ch.permissionOverwrites.delete(member);
ch.permissionsFor(member).has('SendMessages');
await ch.delete();
```

Channel types are `text`, `voice`, `announcement`, `forum` and `media`. Voice channels accept `bitrate` and `userLimit`. Vexel lowercases text channel names and replaces spaces with dashes.

Webhooks: `channel.createWebhook({ name })` returns an object with a `url` you can POST messages to. Use `channel.fetchWebhooks()` and `guild.fetchWebhooks()` to list them.

## Direct messages

```js
await user.send('Hi!');                 // or (await client.users.fetch(id)).send(...)
```

Bots can DM people they share a server with. Vexel protects users from unwanted DMs, so a bot's **first DM to someone arrives as a message request**. They see it only if they accept it, and replies reach you once they do. A bot can never message someone who has blocked it, and gets error code `50007` if it tries. Don't rely on DMs for anything critical, and don't send DMs nobody asked for: people can report and block your bot.

To get DM events, add the `DirectMessages` intent. DM channels are `DMChannel` objects with `send()`, `messages` and `recipient`.

## Threads and scheduled events

### Threads

Threads work in text and announcement channels, and every post in a forum or media channel is a thread too. A thread is a `ThreadChannel`: send, fetch and delete messages in it like any text channel.

```js
// a thread in a text channel, or one started from a message
const thread = await channel.threads.create({ name: 'Raid planning', autoArchiveDuration: 1440 });
const fromMessage = await message.startThread({ name: 'Discuss this' });
await thread.send('Who is in?');

// a forum post: the name plus its first message
const post = await forum.threads.create({ name: 'Bug: login fails', message: { content: 'Steps to reproduce…' }, appliedTags: [forum.availableTags[0].id] });

await thread.setArchived(true);   // creator or Manage Messages
await thread.setLocked(true);     // Manage Messages: only moderators can post
await thread.join(); await thread.members.add(user); await thread.leave();
const active = await channel.threads.fetchActive();
const { threads, hasMore } = await channel.threads.fetchArchived({ limit: 25 });
```

Threads archive themselves after their `autoArchiveDuration` (60, 1440, 4320 or 10080 minutes) without new messages. Sending a message reopens an archived thread unless it's locked. Events: `threadCreate` (thread, newlyCreated), `threadUpdate` (old, new), `threadDelete`, `threadMembersUpdate`.

### Scheduled events

Events belong to a server and happen in a voice channel or somewhere else. People mark themselves **Interested**. Managing events needs **Manage Server**.

```js
const { GuildScheduledEventStatus } = require('vexel.js');
const night = await guild.scheduledEvents.create({
  name: 'Game night', description: 'Bring snacks', scheduledStartTime: new Date(Date.now() + 86400e3), channel: voiceChannel,
});
const meetup = await guild.scheduledEvents.create({
  name: 'Meetup', scheduledStartTime: '2030-05-01T18:00:00Z', scheduledEndTime: '2030-05-01T20:00:00Z', entityMetadata: { location: 'Central Park' },
});
await night.setStatus(GuildScheduledEventStatus.Active);       // or Completed / Canceled
const people = await night.fetchSubscribers({ withMember: true });
await night.setInterested(true);                               // the bot marks itself interested
client.on('guildScheduledEventUserAdd', (event, user) => console.log(`${user.id} is interested in ${event.name}`));
```

Events start and end on their own at their scheduled times (voice events without an end time end 4 hours after starting). Use the `GuildScheduledEvents` intent for `guildScheduledEventCreate`, `…Update`, `…Delete`, `…UserAdd` and `…UserRemove`.

## Invites, audit log, AutoMod, polls and webhooks

```js
// invites (Create Invite to make one; Manage Server to list them all)
const invite = await channel.createInvite({ maxAge: 3600, maxUses: 10 });
console.log(invite.url);
const all = await guild.invites.fetch();
const info = await client.fetchInvite('abc123', { withCounts: true });

// audit log (View Audit Log)
const { AuditLogEvent } = require('vexel.js');
const { entries } = await guild.fetchAuditLogs({ type: AuditLogEvent.MemberBanAdd, limit: 10 });
for (const e of entries.values()) console.log(e.executor?.username, 'banned', e.targetId, e.reason);

// AutoMod: Vexel has one AutoMod setup per server, shown as four rules
const rules = await guild.autoModerationRules.fetch();
const words = rules.find((r) => r.triggerType === 1);
await guild.autoModerationRules.edit(words.id, { enabled: true, triggerMetadata: { keywordFilter: ['spoiler*', 'scam'] } });

// polls (single choice; open for `duration` hours)
const msg = await channel.send({ poll: { question: 'Pizza or tacos?', answers: ['Pizza', 'Tacos'], duration: 4 } });
const voters = await msg.fetchPollVoters(1);
await msg.endPoll();
client.on('messagePollVoteAdd', ({ answerId, message }, userId) => {});

// webhooks
const hook = await channel.createWebhook({ name: 'Deploys' });
await hook.edit({ avatar: './logo.png' });
const { WebhookClient } = require('vexel.js');
const sender = new WebhookClient({ url: hook.url });   // no bot token needed
await sender.send({ content: 'Deployed v2', username: 'CI' });

// server settings, ordering and bulk bans
await guild.edit({ name: 'New name', icon: './icon.png' });
await guild.channels.setPositions([{ channel: rulesChannel, position: 0 }]);
await guild.roles.setPositions([{ role: modRole, position: 5 }]);
const { bannedUsers, failedUsers } = await guild.bans.bulkCreate(['111', '222'], { reason: 'Raid' });
```

Moderation events need the `GuildModeration` intent: `guildBanAdd`, `guildBanRemove` and `guildAuditLogEntryCreate` (the bot also needs View Audit Log). AutoMod blocks arrive as `autoModerationActionExecution` (`AutoModerationExecution` intent and Manage Server). Invites: `inviteCreate` and `inviteDelete` (`GuildInvites`). Webhook changes: `webhooksUpdate` (`GuildWebhooks`).

## Log in with Vexel (OAuth2)

Websites can let people sign in with their Vexel account. Create a client secret and add your redirect URL in **Developer Portal → OAuth2**.

```js
const { OAuth2 } = require('vexel.js');
const oauth = new OAuth2({ clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, redirectUri: 'https://example.com/callback' });

app.get('/login', (req, res) => { req.session.state = crypto.randomUUID(); res.redirect(oauth.authorizeURL({ scopes: ['identify', 'guilds'], state: req.session.state })); });
app.get('/callback', async (req, res) => {
  if (req.query.state !== req.session.state) return res.status(400).end();
  const tokens = await oauth.exchangeCode(req.query.code);           // { accessToken, refreshToken, expiresAt, scopes }
  const me = await oauth.user(tokens.accessToken).getUser();
  const servers = await oauth.user(tokens.accessToken).getGuilds();
  res.send(`Hi ${me.username}, you're in ${servers.length} servers`);
});
```

Scopes: `identify`, `email`, `guilds`, `guilds.members.read`, `connections`. Access tokens last 7 days; `oauth.refresh(refreshToken)` gets new ones. Keep the client secret on your server.

## Sharding

One connection handles any normal bot. For very large bots, run several processes with `new Client({ intents, shard: [id, count] })`: shard `id` receives the servers where `guild_id % count === id`, and DMs go to shard 0.

## Voice and music bots

Vexel voice is peer-to-peer WebRTC: everyone in a channel connects to everyone else directly. A bot joins the same way. The gateway relays the connection setup, and a WebRTC library on the bot's side sends the audio. vexel.js ships an adapter for **werift**, a pure-JavaScript WebRTC stack, and encodes Opus with **opusscript**:

```bash
npm install werift opusscript
# and ffmpeg (https://ffmpeg.org) on your PATH, or set FFMPEG_PATH, to play files and URLs
```

The bot needs the `GuildVoiceStates` intent and the **Connect** permission in the channel. It must also have **Speak** for people to hear it.

```js
const { createAudioPlayer, createAudioResource, AudioQueue, VoiceConnectionStatus } = require('vexel.js');

const channel = interaction.member.voice.channel;          // the channel the person is in
const connection = client.voice.join(channel);            // or channel.join()
await connection.entersState(VoiceConnectionStatus.Ready, 15_000);

const player = createAudioPlayer();
connection.subscribe(player);
player.play(createAudioResource('https://example.com/song.mp3'));   // anything ffmpeg can read
player.pause(); player.unpause(); player.setVolume(0.5); player.stop();

player.on('idle', () => console.log('finished'));
player.on('error', (err) => console.error(err));
```

**Resources:**
- `createAudioResource(pathOrUrlOrStream)`: any format, decoded by ffmpeg. `seek: 30` starts 30 seconds in.
- `createAudioResource(stream, { inputType: 'pcm' })`: raw 48 kHz stereo signed 16-bit little-endian PCM, no ffmpeg needed.
- `createAudioResource(packets, { inputType: 'opus' })`: an iterable of ready-made 20 ms Opus packets (volume doesn't apply).

**Queue:**

```js
const queue = new AudioQueue(player);
queue.add({ title: 'Song A', resource: () => createAudioResource('a.mp3') });  // resources are created when the track starts
queue.add({ title: 'Song B', resource: () => createAudioResource('b.mp3') });
queue.skip(); queue.shuffle(); queue.setLoop('queue'); queue.stop();
queue.on('trackStart', (t) => channel.send(`Now playing ${t.title}`));
queue.on('empty', () => connection.destroy());
```

**Connection lifecycle:** the connection moves through `signalling` → `ready`, then `disconnected` (kicked, channel deleted, or the bot lost access) or `destroyed`. Listen to `stateChange`, `peerJoin` and `peerLeave`. Call `connection.rejoin({ channelId })` to move. Use `setSelfMute()` and `setSelfDeaf()`. Leave with `connection.destroy()`. If a moderator moves the bot, it follows automatically. A short gateway drop that resumes keeps the bot in voice. If the session can't be resumed (the `invalidated` event), the bot has left voice; call `connection.rejoin()`.

**Limits:**
- A bot is in **one voice channel at a time**; joining another moves it.
- Bots can't receive audio yet.
- Audio goes to every person in the channel separately, so a busy channel (up to 25 people) uses that many times the upload bandwidth. Host music bots somewhere with good upload speed.
- By default the bot uses STUN only. That works when the bot runs on a server with a public address, which is typical, because people's apps already relay through Vexel's TURN server when they need to. If your bot is behind a strict NAT, pass `client.voice.join(channel, { useTurn: true })`.

**Your own adapter:** `client.voice.join(channel, { adapterCreator })` accepts any object with `addPeer`, `removePeer`, `handleSignal`, `sendOpus`, `connectedPeers` and `destroy`. See `src/voice/WeriftAdapter.js`. Use this to plug in a different WebRTC library.

See `examples/music-bot` for a complete bot.

## Presence and profile

```js
client.user.setActivity('/help', { type: ActivityType.Listening });
client.user.setStatus('idle');                       // online, idle, dnd, invisible
client.user.setPresence({ status: 'dnd', activities: [{ name: 'maintenance', type: ActivityType.Playing }] });
await client.user.edit({ username: 'New Name', avatar: fs.readFileSync('avatar.png') });
new Client({ intents, presence: { activities: [{ name: 'Starting up' }] } });   // presence at login
```

## Reconnecting and resuming

vexel.js keeps the connection healthy for you:
- **Heartbeats:** if the server stops acknowledging them, the connection is treated as dead and replaced.
- **Resuming:** after a drop, vexel.js resumes the same session for up to 90 seconds, and the server replays every event you missed in order. You get a `resumed` event. If the session can't be resumed, vexel.js starts a new one and you get `invalidated`.
- **Backoff:** reconnects wait 1s, 2s, 4s… up to 60 seconds, with some randomness.
- **Fatal errors** stop retrying and reject `login()` or emit `error` with a clear message: a bad token (`GATEWAY_4004`) or disallowed intents (`GATEWAY_4014`).
- **Command limit:** gateway commands such as presence updates and member requests are limited to 120 a minute; vexel.js queues them for you.

`client.destroy()` closes everything cleanly and tells the server not to keep the session.

## Rate limits

Vexel limits how fast bots can act. For example, a bot can send 5 messages per channel every 5 seconds, make 50 requests per second overall, and add 1 reaction every 250 ms per channel. vexel.js reads the rate-limit headers, queues requests per route, and waits when needed, so your code doesn't have to. It also retries `429` responses and temporary server errors (up to 3 times).

- `client.on('rateLimited', (info) => …)` tells you when it waits.
- `new Client({ rest: { rejectOnRateLimit: true } })` throws `RateLimitError` instead of waiting. You can also pass a function that decides per request.
- `rest: { timeout: 15000, retries: 3 }` tunes the HTTP behaviour.

## Errors

| Error | When |
|---|---|
| `VexelAPIError` | the API refused a request: `status` (HTTP), `code` (API code), `method`, `path`, `rawError` |
| `RateLimitError` | with `rejectOnRateLimit` |
| `VexelError` | vexel.js itself, with a string `code` such as `INTERACTION_EXPIRED`, `MISSING_INTENT`, `GATEWAY_4014`, `FFMPEG_MISSING`, `VOICE_ADAPTER` or `COMMAND_OPTION_MISSING` |

Common API codes are listed in `VexelAPIError.Codes`, including `UnknownChannel` 10003, `UnknownMember` 10007, `UnknownMessage` 10008, `MissingAccess` 50001, `CannotSendMessagesToThisUser` 50007, `MissingPermissions` 50013, `InvalidFormBody` 50035 and `UnknownInteraction` 10062.

```js
try { await member.kick(); }
catch (err) {
  if (err instanceof VexelAPIError && err.code === VexelAPIError.Codes.MissingPermissions) return interaction.reply({ content: "I'm not allowed to do that.", ephemeral: true });
  throw err;
}
```

## Using another API address

vexel.js talks to the public Vexel API by default. To use another Vexel server (for example a development copy), pass `new Client({ api: 'https://your-host/api/v10', intents })` or set `VEXEL_API`.


---

# vexel.js API reference

Full TypeScript signatures are in [`src/index.d.ts`](../src/index.d.ts). This page lists every public class and what it's for.

## Client

`new Client(options)` takes:
- `intents`: required. A number, or an array of intent values or names.
- `api`: the API base URL. Defaults to the public API, or the `VEXEL_API` environment variable.
- `rest`: `{ timeout, retries, rejectOnRateLimit, globalRequestsPerSecond }`.
- `presence`: the presence to set at login.
- `commands`: `{ sync = true, clearGlobal = false }`.
- `messageCacheSize`: messages kept per channel (default 200).
- `failIfNotExists`: whether replying to a deleted message errors (default false).
- `readyTimeout`: how long to wait for servers before emitting `ready` anyway (default 15000 ms).
- `debug`: emit verbose `debug` events.

| Member | Description |
|---|---|
| `login(token?)` | Connects. Resolves with the token once the gateway is ready; rejects on a bad token or disallowed intents |
| `destroy()` | Leaves voice, closes the gateway (not resumable) and clears caches |
| `isReady()`, `readyAt`, `uptime`, `ping` | Connection state |
| `user` | `ClientUser` |
| `application` | `{ id, name, description, icon, flags, commands: ApplicationCommandManager }` |
| `guilds`, `channels`, `users` | Managers with `cache` (a Collection) and `fetch()` |
| `commands` | `CommandManager`: registered commands with handlers |
| `components` | `ComponentRouter`: button, select and modal handlers by `customId` |
| `voice` | `VoiceManager` |
| `rest` | `REST` |
| `gateway` | `Gateway` |
| `generateInvite({ scopes, permissions, guild })` | Builds an invite link |
| `on(event, listener)` | See [Events](guide.md#events) |

## Collection

A `Map` with `first`, `last`, `find`, `findKey`, `filter`, `map`, `mapValues`, `some`, `every`, `reduce`, `sort`, `sorted`, `partition`, `random` and `toJSON`.

## Structures

| Class | Key members |
|---|---|
| `User` | `id`, `username`, `displayName`, `bot`, `avatarURL()`, `displayAvatarURL()`, `createDM()`, `send()`, `toString()` |
| `ClientUser` | `setPresence()`, `setActivity()`, `setStatus()`, `edit({ username, avatar })`, `setUsername()`, `setAvatar()` |
| `Guild` | `id`, `name`, `icon`, `ownerId`, `memberCount`, `channels`, `roles`, `members`, `bans`, `voiceStates.cache`, `presences`, `systemChannel`, `commands`, `iconURL()`, `fetch()`, `fetchOwner()`, `leave()`, `fetchWebhooks()`, `fetchEmojis()` |
| `GuildMember` | `user`, `nickname`, `displayName`, `roles`, `permissions`, `joinedAt`, `communicationDisabledUntil`, `voice`, `manageable`, `kickable`, `bannable`, `moderatable`, `edit()`, `setNickname()`, `kick()`, `ban()`, `timeout()`, `permissionsIn()`, `send()` |
| `GuildMemberRoleManager` (`member.roles`) | `cache`, `highest`, `hoist`, `color`, `has()`, `add()`, `remove()`, `set()` |
| `Role` | `name`, `color`, `hexColor`, `hoist`, `position`, `permissions`, `managed`, `mentionable`, `members`, `editable`, `edit()`, `setName()`, `setColor()`, `setPermissions()`, `setPosition()`, `delete()`, `comparePositionTo()` |
| `VoiceState` | `channelId`, `channel`, `member`, `selfMute`, `selfDeaf`, `serverMute`, `serverDeaf`, `streaming`, `setMute()`, `setDeaf()`, `setChannel()`, `disconnect()` |
| `Message` | `content`, `author`, `member`, `channel`, `guild`, `embeds`, `attachments`, `components`, `mentions`, `reference`, `pinned`, `createdAt`, `editedAt`, `url`, `reply()`, `edit()`, `delete()`, `react()`, `pin()`, `unpin()`, `fetch()`, `fetchReference()`, `awaitMessageComponent()`, `reactions` (`removeAll()`, `removeEmoji()`, `removeUser()`, `fetchUsers()`) |

## Channels

Every channel has `id`, `type`, `isTextBased()`, `isVoiceBased()`, `isDMBased()`, `fetch()`, `delete()` and `toString()`.

**Server channels (`GuildChannel`)** add `guild`, `name`, `position`, `parentId`, `permissionOverwrites` (`edit`, `create`, `delete`), `permissionsFor()`, `edit()`, `setName()`, `setPosition()` and `clone()`.

**Text-based channels (`TextChannel`, `AnnouncementChannel`, `VoiceChannel`, `DMChannel`)** add:
- `send()`, `sendTyping()`, `bulkDelete()`, `awaitMessages()`
- `messages`, with `fetch()`, `iterate()`, `fetchPinned()`, `edit()`, `delete()`, `pin()`, `unpin()` and `react()`
- `fetchWebhooks()` and `createWebhook()`

**Per type:**
- `TextChannel`: `topic`, `rateLimitPerUser`, `setTopic()`, `setRateLimitPerUser()`, `setNSFW()`
- `VoiceChannel`: `bitrate`, `userLimit`, `members`, `joinable`, `join()`, `setBitrate()`, `setUserLimit()`
- `CategoryChannel`: `children`
- `ForumChannel`: `topic`
- `DMChannel`: `recipient`

## Managers

| Manager | Methods |
|---|---|
| `client.guilds` | `fetch()` (all), `fetch(id)` |
| `client.channels` | `fetch(id)` |
| `client.users` | `fetch(id)`, `send(user, options)` |
| `guild.channels` | `fetch()`, `create(options)`, `edit()`, `delete()` |
| `guild.roles` | `fetch()`, `create(data)`, `edit()`, `delete()`, `everyone`, `highest`, `comparePositions()` |
| `guild.members` | `fetch(id \| { user, query, limit, withPresences })`, `fetchMe()`, `me`, `search()`, `edit()`, `kick()`, `ban()`, `unban()`, `addRole()`, `removeRole()` |
| `guild.bans` | `fetch()`, `create(user, { reason, deleteMessageSeconds })`, `remove()` |

## Interactions

All interactions share `id`, `user`, `member`, `guild`, `channel`, `memberPermissions`, `appPermissions`, `locale`, `replied`, `deferred`, `responseTimeLeft` and the type guards (`isChatInputCommand()` and so on).

**Responding** (commands, components and modal submits): `reply()`, `deferReply()`, `editReply()`, `deleteReply()`, `fetchReply()`, `followUp()`, `showModal()` and `awaitModalSubmit()`.

**Per kind:**
- `ChatInputCommandInteraction`: `commandName`, `commandId`, `options` (a `CommandInteractionOptionResolver`).
- `UserContextMenuCommandInteraction`: `targetUser`, `targetMember`.
- `MessageContextMenuCommandInteraction`: `targetMessage`.
- Component interactions (`ButtonInteraction`, the `*SelectMenuInteraction` classes):
  - `customId`, `componentType`, `message`, `values`
  - for user, role, mentionable and channel selects: `users`, `members`, `roles`, `channels`
  - `update()` and `deferUpdate()`
- `ModalSubmitInteraction`: `customId`, `fields.getTextInputValue(id)`, `fields.fields`, `message`, `update()`, `deferUpdate()`.
- `AutocompleteInteraction`: `commandName`, `options.getFocused(full?)`, `respond(choices)`.

`CommandInteractionOptionResolver` has `get`, `getString`, `getInteger`, `getNumber`, `getBoolean`, `getUser`, `getMember`, `getChannel`, `getRole`, `getMentionable`, `getAttachment`, `getSubcommand`, `getSubcommandGroup` and `getFocused`.

## Commands

**`CommandManager` (`client.commands`):**
- `register(...definitions)`, `unregister(name, { type, guildId })`, `get(name, type?, guildId?)`, `sync()`.
- Each definition is `{ name, description, type ('chat' | 'user' | 'message'), options, guildId, defaultMemberPermissions, dmPermission, nsfw, execute(i), autocomplete(i), subcommands }`.

**`ApplicationCommandManager` (`client.application.commands`, `guild.commands`):** `fetch()`, `set(list)`, `create()`, `edit()`, `delete()` and `forGuild(id)`.

**`ComponentRouter` (`client.components`):** `onButton(match, handler)`, `onSelect()` and `onModal()`. `match` is an exact string, a `'prefix:'` string, a RegExp or a function. The handler receives `(interaction, args, client)`.

## Builders

`EmbedBuilder`, `ActionRowBuilder`, `ButtonBuilder`, `StringSelectMenuBuilder`, `UserSelectMenuBuilder`, `RoleSelectMenuBuilder`, `MentionableSelectMenuBuilder`, `ChannelSelectMenuBuilder`, `ModalBuilder`, `TextInputBuilder`, `AttachmentBuilder`, `SlashCommandBuilder` (with `add*Option`, `addSubcommand`, `addSubcommandGroup`) and `ContextMenuCommandBuilder`. Anywhere a builder is accepted, a plain object in the API shape works too.

## Voice

| Class / function | Description |
|---|---|
| `client.voice.join(channel, { selfMute, selfDeaf = true, useTurn, adapterCreator })` | Returns a `VoiceConnection` |
| `VoiceConnection` | `status`, `channelId`, `peers`, `readyPeers`, `subscribe(player)`, `entersState(status, ms)`, `rejoin()`, `setSelfMute()`, `setSelfDeaf()`, `destroy()`. Events: `stateChange`, `ready`, `disconnected`, `destroyed`, `peerJoin`, `peerLeave`, `error` |
| `createAudioPlayer({ noSubscriber })` → `AudioPlayer` | `play()`, `pause()`, `unpause()`, `stop()`, `setVolume(0-2)`, `status`. Events: `playing`, `paused`, `idle`, `buffering`, `stateChange`, `error` |
| `createAudioResource(input, { inputType, seek, volume, metadata, ffmpegPath, ffmpegArgs })` → `AudioResource` | `inputType` is `'arbitrary'` (ffmpeg), `'pcm'` or `'opus'` |
| `AudioQueue(player)` | `add(track)`, `skip()`, `clear()`, `shuffle()`, `remove(i)`, `setLoop('off' \| 'track' \| 'queue')`, `stop()`, `current`, `tracks`. Events: `trackStart`, `trackEnd`, `empty`, `error` |

## REST and Gateway

**`REST`:**
- `get`, `post`, `put`, `patch`, `delete` and `request(method, path, { body, files, query, reason, auth })`.
- Emits `rateLimited`, `response` and `debug`.
- Use it directly for endpoints that have no helper.

**`Gateway`:**
- `connect()`, `send(payload)` (rate-limited queue), `sendNow(payload)`, `reconnect()`, `destroy()`.
- Properties: `sessionId`, `seq`, `ping`, `status`.
- Events: `dispatch`, `ready`, `resumed`, `close`, `reconnecting`, `invalidated`, `error`, `debug`.

## Threads

| Member | Description |
|---|---|
| `channel.threads.create({ name, autoArchiveDuration, startMessage })` | Starts a thread in a text or announcement channel |
| `forum.threads.create({ name, message, appliedTags })` | Creates a forum / media post with its first message |
| `channel.threads.fetchActive()`, `fetchArchived({ before, limit })` | Lists threads under a channel |
| `guild.fetchActiveThreads()` | Active threads in the whole server |
| `message.startThread({ name })` | A thread from a message |
| `ThreadChannel` | A text channel plus `archived`, `locked`, `autoArchiveDuration`, `ownerId`, `appliedTags`, `edit()`, `setArchived()`, `setLocked()`, `setAppliedTags()`, `join()`, `leave()`, `members` (`fetch`, `add`, `remove`) |
| `forum.availableTags`, `forum.setAvailableTags(tags)` | Forum tags |

## Scheduled events

| Member | Description |
|---|---|
| `guild.scheduledEvents.fetch(id?, { withUserCount })` | One event or all upcoming ones |
| `create({ name, scheduledStartTime, scheduledEndTime, channel, entityMetadata: { location }, description })` | Needs Manage Server. Voice events take `channel`; others take `location` and an end time |
| `edit(event, data)`, `delete(event)`, `event.setStatus(status)` | `GuildScheduledEventStatus`: Scheduled 1, Active 2, Completed 3, Canceled 4 |
| `fetchSubscribers(event, { limit, after, withMember })` | People who are interested |
| `event.setInterested(on)` | Vexel extension: the bot marks itself interested |

## Invites, audit log and AutoMod

| Member | Description |
|---|---|
| `channel.createInvite({ maxAge, maxUses, temporary, unique })` | An `Invite` (`code`, `url`, `uses`, `maxUses`, `expiresAt`, `inviter`) |
| `guild.invites.fetch({ channel? })`, `guild.invites.delete(code)` | Manage Server (or Manage Channels for one channel) |
| `client.fetchInvite(code, { withCounts })`, `client.deleteInvite(code)` | Any invite |
| `guild.fetchAuditLogs({ type, user, before, after, limit })` | `{ entries }` of `GuildAuditLogsEntry` (`action`, `executor`, `targetId`, `reason`, `vexelAction`). `AuditLogEvent` has the type numbers |
| `guild.autoModerationRules.fetch(id?)`, `create()`, `edit(id, data)`, `delete(id)` | Rules: keyword (custom words), spam, keyword presets (flagged words) and mention spam |

## Polls and webhooks

| Member | Description |
|---|---|
| `channel.send({ poll: { question, answers, duration } })` | A single-choice poll, open for `duration` hours (default 24) |
| `message.poll`, `message.fetchPollVoters(answerId)`, `message.endPoll()` | Results, voters (answers start at 1), ending early |
| `channel.fetchWebhooks()`, `channel.createWebhook({ name })`, `guild.fetchWebhooks()`, `client.fetchWebhook(id)` | `Webhook` objects with `edit({ name, avatar, channel })`, `delete()`, `send()` |
| `new WebhookClient({ url })` | Posts with a webhook URL and no bot token: `send()`, `editMessage()`, `deleteMessage()`, `fetchMessage()` |

## Servers

| Member | Description |
|---|---|
| `guild.edit({ name, description, icon, banner, discoverable })`, `setName()`, `setIcon()`, `setBanner()` | Manage Server. Images: Buffer, file path, URL or data URI |
| `guild.channels.setPositions([{ channel, position }])`, `guild.roles.setPositions([{ role, position }])` | Reordering |
| `guild.bans.bulkCreate(users, { reason })` | Up to 200 at once (Ban Members + Manage Server) |
| `guild.fetchVoiceState(user)`, `guild.fetchStickers()`, `guild.deleteEmoji(id)` | Voice states and expressions |

## OAuth2

`new OAuth2({ clientId, clientSecret, redirectUri })`: `authorizeURL({ scopes, state })`, `exchangeCode(code)`, `refresh(refreshToken)`, `clientCredentials()`, `revoke(token)`, and `user(accessToken)` with `getUser()`, `getGuilds()`, `getGuildMember(guildId)`, `getConnections()`, `getAuthorization()`. `OAuth2Scopes` lists the scopes.

## Sharding

`new Client({ intents, shard: [id, count] })` sends `shard` in IDENTIFY. Shard `id` gets the servers where `guild_id % count === id`; DMs go to shard 0.

## Constants

`GatewayIntentBits` (alias `Intents`), `PermissionFlagsBits`, `ChannelType`, `ApplicationCommandType`, `ApplicationCommandOptionType`, `InteractionType`, `InteractionResponseType`, `ComponentType`, `ButtonStyle`, `TextInputStyle`, `MessageFlags`, `ActivityType`, `Events`, `GatewayOpcodes`, `FatalCloseCodes`, `UnsupportedEvents`, `Colors`, `VoiceConnectionStatus`, `AudioPlayerStatus` and `StreamType`.

## Gateway protocol notes (for other languages)

vexel.js uses the Discord-compatible gateway at `wss://<host>/gateway` (v10, JSON, optional zlib-stream). It supports HELLO, IDENTIFY, RESUME (sessions stay resumable for 90 seconds after a drop, with missed events replayed), HEARTBEAT and ACK, INVALID_SESSION, REQUEST_GUILD_MEMBERS and PRESENCE_UPDATE.

Vexel adds these voice operations:

| Op | Direction | Payload |
|---|---|---|
| 4 | to server | `{ guild_id, channel_id, self_mute, self_deaf }`. Joins voice; `channel_id: null` leaves |
| 40 | to server | `{ to, data }`. Relays a WebRTC `{ description }` or `{ candidate }` to a person in the channel |
| 41 | to server | `{ self_mute, self_deaf }`. Updates the bot's own voice flags |
| `VOICE_SIGNAL` (dispatch) | to bot | `{ type: 'joined', channelId, peers, bitrate, ice_servers }`, `{ type: 'rtc', from, data }`, `{ type: 'error', message }`, `{ type: 'kicked' }` or `{ type: 'moved', channelId }` |

When a bot joins, it sends an offer to everyone already in the channel. People who join later send offers to the bot, and it answers. Collisions are settled with the "perfect negotiation" rule: the side with the larger ID is polite.
