Skip to main content

Build a command bot

This guide builds a bot with four commands: You need a bot token and a channel where the bot can read history and send messages. Use Node 22+ or Bun. For Node 20, follow the WebSocket adapter setup.

Install and run

Save the following as bot.mjs:
Run it with your raw bot token:
With Bun, run bun bot.mjs. Set FLUXER_ORIGIN when using another instance. Try !help after the connected username appears in the terminal.

How the pieces fit

Client.connect() discovers the instance, creates the REST helpers, and opens the gateway. messageCreate delivers a Message object. Its reply() method sends through REST and attaches a reference to the incoming message. By default, replies disable mention parsing and do not ping the replied-to author. The history iterator fetches older messages only while the loop needs them. The before cursor excludes the command itself. Returning after the first human message also ends the iterator; it does not fetch the rest of the channel. Permission checks need the member, every guild role, and the channel’s overwrites. The result is a permission mask. A timeout or another server policy can still prevent an action; see the permissions guide. An async handler that rejects reaches the error listener. Handlers may overlap, so keep shared application state safe for concurrent commands. For work that must be saved in dispatch order, use durable dispatch processing.

Add your own command

Add another case in the switch. To send a file, pass a Blob through the reply’s options. To edit a response later, keep the Message returned by reply() and call its edit() method. The messages guide shows both patterns. For channel operations, fetch a Channel. For member operations, fetch a Guild and use guild.members. If there is no convenience method for an endpoint, call client.rest.request() with the route template. Find constructors, properties, and methods in the class reference. The docs index links the more detailed task guides.