# Fluxerly.js guides
> Fluxerly.js is a Fluxer-native bot SDK for JavaScript, TypeScript and Effect. Requires Node.js 26.13 or newer, ESM and TypeScript 7
Voice: Gateway signaling works today through `client.voice` (`join`, `leave`, `updateState`) with typed `voiceServerUpdate`, `voiceSignal`, `voiceStateUpdate` and `gatewayError` events, alongside member voice controls and voice notes. Built-in audio and video transport is planned for Fluxer's upcoming native voice engine so bots avoid lock-in to a temporary media layer, and bots needing live media today can pass `voiceServerUpdate` credentials directly to their own media client
These files describe SDK version 1004.0.0
# Build a Fluxer bot
Fluxerly.js connects Node.js applications to Fluxer.
It supports sending messages, responding to events and building bots in JavaScript or TypeScript
## Start a bot
1. [Create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md): Create the Fluxer application, copy its token and invite the bot to a server
2. [Quick start](https://fluxerly.neontechspace.com/docs/quick-start.md): Install the SDK and make the bot answer !ping
3. [Build a small bot](https://fluxerly.neontechspace.com/docs/small-bot.md) with commands, an embed and a welcome message, or copy a complete [example bot](https://fluxerly.neontechspace.com/docs/examples.md)
The [core concepts](https://fluxerly.neontechspace.com/docs/core-concepts.md) explain the few ideas behind every guide. For an application that already uses Effect, start with [the Effect bot guide](https://fluxerly.neontechspace.com/docs/effect-first-bot.md)
## Run it in production
[Configuration](https://fluxerly.neontechspace.com/docs/configuration.md), [logging](https://fluxerly.neontechspace.com/docs/logging.md), [deploying](https://fluxerly.neontechspace.com/docs/deploying.md), [sharding](https://fluxerly.neontechspace.com/docs/sharding.md), [supervision](https://fluxerly.neontechspace.com/docs/application-supervision.md) and [testing](https://fluxerly.neontechspace.com/docs/testing.md) cover a bot that keeps running
## Get unstuck
[Where do I…?](https://fluxerly.neontechspace.com/docs/where-do-i.md) finds the guide for a task. [Troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md), the [error and log codes](https://fluxerly.neontechspace.com/docs/codes/) and the [FAQ](https://fluxerly.neontechspace.com/docs/faq.md) help when something fails
## Voice
Fluxerly handles gateway voice signaling cleanly today through `client.voice` (`join`, `leave`, `updateState`) plus typed `voiceStateUpdate`, `voiceServerUpdate`, `voiceSignal` and `gatewayError` refusal events, alongside member voice controls, voice notes and audio or video attachments. Built-in audio transport and playback are planned for Fluxer's own voice engine so bots avoid lock-in to a temporary media layer, and bots needing audio today can pass the typed grant straight to their own media client. See [voice controls and signaling](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#voice-controls-versus-a-voice-connection)
## Find a method
The [API reference](https://fluxerly.neontechspace.com/docs/api/) lists the available methods and types.
Use search to jump to a name such as `createClient`
---
# Publish and follow announcement channels
Create announcement channels, publish messages, follow them in the same community or another one and handle published copies
An announcement channel publishes messages to the text channels that follow it, in the same community or another one. Sending a message to the announcement channel does not publish it
These helpers take the existing `client` from the [first bot](https://fluxerly.neontechspace.com/docs/quick-start.md) or [first Effect bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md). Pass decimal IDs from trusted application configuration. The default API returns a [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result). Native Effect helpers return an [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect), run with `yield*` inside the application program
## Create an announcement channel
Creating a channel needs `ManageChannels` in its community. Set `type` to `ChannelType.Announcement`, whose protocol value is 5
```ts
import { ChannelType, type Client } from "@neontechspace/fluxerly"
export async function createAnnouncements(client: Client, guildId: string) {
return await client.channels.create(guildId, {
type: ChannelType.Announcement,
name: "announcements",
topic: "Published community updates",
})
}
```
The returned announcement channel has the `GuildAnnouncementChannel` shape. It has the same message and topic fields as a text channel
With the native Effect API:
```ts
import { ChannelType, type Client } from "@neontechspace/fluxerly/effect"
export function createAnnouncementsWithEffect(client: Client, guildId: string) {
return client.channels.create(guildId, {
type: ChannelType.Announcement,
name: "announcements",
topic: "Published community updates",
})
}
```
## Convert an existing channel
Use `channels.edit` with a new type to convert a text channel into an announcement channel. The same helper can convert it back to `ChannelType.Text`. Both directions need `ManageChannels`
```ts
import { ChannelType, type Client } from "@neontechspace/fluxerly"
export async function setAnnouncementChannel(client: Client, channelId: string, enabled: boolean) {
return await client.channels.edit(channelId, {
type: enabled ? ChannelType.Announcement : ChannelType.Text,
})
}
```
A text channel that follows an announcement channel cannot become one. Delete its follower webhooks first. Converting an announcement channel back to text removes its follower webhooks asynchronously. A successful edit does not wait for that removal
The SDK emits a `guildChannelUpdate` event with the new type. Code that handles channel updates must check the new `type` rather than retaining the old channel shape
With the native Effect API:
```ts
import { ChannelType, type Client } from "@neontechspace/fluxerly/effect"
export function setAnnouncementChannelWithEffect(client: Client, channelId: string, enabled: boolean) {
return client.channels.edit(channelId, {
type: enabled ? ChannelType.Announcement : ChannelType.Text,
})
}
```
## Send a message, then publish it
Publishing sends copies to every following channel. First send a new message, not a reply, to the announcement channel, then pass the returned message to `messages.publish`
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function publishUpdate(client: Client, channelId: string, content: string) {
const sent = await client.messages.send(channelId, content)
if (sent.isErr()) return sent
const published = await client.messages.publish(sent.value)
if (published.isErr()) {
console.warn(`Message ${sent.value.id} in channel ${channelId} was sent, but publishing it is not confirmed`)
}
return published
}
```
A failed send skips publication. A failed publish leaves the sent message posted, so the helper logs its ID and returns the failure unchanged
Fluxer's API and flags call publishing crossposting: `MessageFlags.Crossposted` marks the source and `MessageFlags.IsCrosspost` marks each copy. Completion means Fluxer accepted publication, not that every copy has arrived. A bot that can see a following channel receives each copy as a `messageCreate` event
With the native Effect API, a failed send skips publication and a failed publish logs the sent message's ID:
```ts
import { Effect } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function publishUpdateWithEffect(client: Client, channelId: string, content: string) {
return Effect.gen(function* () {
const sent = yield* client.messages.send(channelId, content)
return yield* client.messages.publish(sent).pipe(
Effect.tapError(() =>
Effect.logWarning(`Message ${sent.id} in channel ${channelId} was sent, but publishing it is not confirmed`),
),
)
})
}
```
Publication limits and later changes
Only a message that is not a reply, forward, system notice or published copy can be published, and only once. It must be in an announcement channel. Publishing someone else's message needs `ManageMessages`. Fluxer limits publication to 10 messages per channel per hour
Editing the source message updates its published copies later. Deleting the source does not delete the copies. Fluxer marks them with `MessageFlags.SourceMessageDeleted`, changes their text to `[Original message deleted]` and removes their attachments
The [messages guide](https://fluxerly.neontechspace.com/docs/messages.md#reply-to-a-message-and-check-what-happened) explains which flags sends and edits accept
If sending succeeds but publication fails, the source message stays posted, which is why the helpers log its ID. Before publishing again, fetch that message and check `MessageFlags.Crossposted`. Fluxer sets the flag before it finishes the request and clears it only when queuing the copies fails, so a failed publish can still leave the message published. Do not rerun the whole helper after an [uncertain write](https://fluxerly.neontechspace.com/docs/reliability.md), because that can send another source message
## Follow an announcement channel from a text channel
The source is an announcement channel. The target is a text channel in the same community or another one. The bot needs `ManageWebhooks` in the target's community, plus `ViewChannel` and `ManageWebhooks` on the target channel. The bot must also be able to view the source channel
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function followAnnouncements(client: Client, sourceChannelId: string, targetChannelId: string) {
return await client.channels.follow(sourceChannelId, { targetChannelId })
}
```
Following creates a follower webhook in the target channel. The result contains `channelId` for the followed announcement channel and `webhookId` for the new follower webhook in the target. Keep that webhook ID to unfollow later. Fluxer usually posts a `MessageType.ChannelFollowAdd` notice in the target, but the notice is not guaranteed. Do not wait for it to decide whether following succeeded
With the native Effect API:
```ts
import type { Client } from "@neontechspace/fluxerly/effect"
export function followAnnouncementsWithEffect(client: Client, sourceChannelId: string, targetChannelId: string) {
return client.channels.follow(sourceChannelId, { targetChannelId })
}
```
An application cannot send messages through a follower webhook. It has no token, so `createWebhookClient` cannot use it. The normal `client.webhooks.edit` method can rename it or move it to another text channel in the same community, but cannot change its avatar
## See follower counts and unfollow
Fetch the number of following channels and distinct receiving communities with `channels.fetchFollowerStats`. Fluxer can cache these counts for up to a minute, so a new follow or unfollow need not appear immediately
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function readFollowerCounts(client: Client, channelId: string) {
const result = await client.channels.fetchFollowerStats(channelId)
if (result.isErr()) return result
return { channels: result.value.channelCount, communities: result.value.guildCount }
}
export async function unfollowAnnouncements(client: Client, webhookId: string) {
return await client.webhooks.delete(webhookId)
}
```
Deleting the follower webhook stops that target channel following the source. Use the `webhookId` from the follow result, or find the follower webhook through `client.webhooks.fetchForChannel`. Check `webhook.type === WebhookType.ChannelFollower` before treating an existing webhook as a follow. Deleting webhooks needs `ManageWebhooks`
With the native Effect API:
```ts
import { Effect } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function readFollowerCountsWithEffect(client: Client, channelId: string) {
return client.channels.fetchFollowerStats(channelId).pipe(
Effect.map(stats => ({ channels: stats.channelCount, communities: stats.guildCount })),
)
}
export function unfollowAnnouncementsWithEffect(client: Client, webhookId: string) {
return client.webhooks.delete(webhookId)
}
```
## React to copies and follow notices
Published copies have `MessageFlags.IsCrosspost`. Follow notices have `MessageType.ChannelFollowAdd`. Register a `messageCreate` handler before connecting, and check these values before any check that skips bot or webhook authors so webhook-delivered copies are not skipped
```ts
import { MessageFlags, MessageType, type Client, type Message } from "@neontechspace/fluxerly"
export function observeAnnouncements(client: Client, observe: (message: Message) => void) {
return client.on("messageCreate", message => {
const isCopy = ((message.flags ?? 0) & MessageFlags.IsCrosspost) !== 0
const isFollowNotice = message.type === MessageType.ChannelFollowAdd
if (isCopy || isFollowNotice) observe(message)
})
}
```
The returned subscription stops with the client. Call its `close()` method to stop it earlier. The [events guide](https://fluxerly.neontechspace.com/docs/events-and-collectors.md) covers registration and delivery limits
With the native Effect API, registration belongs to the scope that runs it. Keep that scope open while the handler is needed:
```ts
import { Effect } from "effect"
import { MessageFlags, MessageType, type Client, type Message } from "@neontechspace/fluxerly/effect"
export function observeAnnouncementsWithEffect(client: Client, observe: (message: Message) => void) {
return client.on("messageCreate", message => Effect.sync(() => {
const isCopy = ((message.flags ?? 0) & MessageFlags.IsCrosspost) !== 0
const isFollowNotice = message.type === MessageType.ChannelFollowAdd
if (isCopy || isFollowNotice) observe(message)
}))
}
```
## Find where a copy came from
A published copy or follow notice can carry `message.messageReference`. This received `MessageContextReference` always has a source `channelId`, but its `id` is optional. A follow notice points only at the source channel. Check `id` before using the reference to fetch or reply to a specific message
The `messages.fetchCrosspostSource` method takes the copy or notice itself, not its source reference. It returns `{ guild }`, a public snapshot of the source community. When the reference has an ID, the helper below also fetches the source message. If the bot cannot read it, the helper returns that failure
```ts
import type { Client, Message } from "@neontechspace/fluxerly"
export async function readAnnouncementSource(client: Client, message: Message) {
const source = await client.messages.fetchCrosspostSource(message)
if (source.isErr()) return source
const reference = message.messageReference
if (!reference?.id) return { guild: source.value.guild }
const original = await client.messages.fetch({ channelId: reference.channelId, id: reference.id })
if (original.isErr()) return original
return { guild: source.value.guild, message: original.value }
}
```
The public community snapshot includes its ID, name, description, icon, banner, public features, custom badge IDs and whether it is discoverable. Member and presence counts can be `null`. This read does not join the community or grant access to its channels. Fetching the original message can fail even when the public community read succeeds
With the native Effect API:
```ts
import { Effect } from "effect"
import type { Client, Message } from "@neontechspace/fluxerly/effect"
export function readAnnouncementSourceWithEffect(client: Client, message: Message) {
return Effect.gen(function* () {
const source = yield* client.messages.fetchCrosspostSource(message)
const reference = message.messageReference
if (!reference?.id) return { guild: source.guild }
const original = yield* client.messages.fetch({ channelId: reference.channelId, id: reference.id })
return { guild: source.guild, message: original }
})
}
```
Follower webhook metadata can also include `sourceGuild` and `sourceChannel`. Those fields appear only while the source exists and is visible to the webhook's creator. Their absence alone does not prove the source was deleted
## Handle permission and delivery failures
Fluxer checks permissions on the final request. Local [permission checks](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md) can help explain a failure, but cannot authorize an action. Creating or converting channels needs `ManageChannels`. Following and managing follower webhooks needs `ManageWebhooks`. Publishing another author's message needs `ManageMessages`. Following also fails for a duplicate follow, incompatible age-restriction or content-warning settings, a full webhook limit, or a community with announcements disabled through the `ANNOUNCEMENT_CHANNELS_DISABLED` feature
The default API returns expected failures in a Result. Check `isErr()` before reading `value`, and use `describeError` to report a failure without logging credentials. Native Effects carry expected failures in their error channel. Use `Effect.match` as shown in [Effect workflows](https://fluxerly.neontechspace.com/docs/effect-workflows.md) when the application needs to turn success or failure into a value
A connected gateway is needed to observe conversions, copies and follow notices, not to make these HTTP requests. A successful request does not wait for later gateway delivery. Identify each copy by its own message ID, because a replayed event can deliver the same copy again
---
# Supervise a critical bot worker
Keep gateway and worker health separate, then choose a fail or restart policy
A bot started with `runBot` is already supervised: The runner watches the connection and every subscription it registered, and stops the bot with `CriticalWorkerStoppedError` if one closes. That includes a handler or command router set to `overflow: "stop"` whose queue fills, and the error then names the event and the exceeded limit. This page is for applications that create the client with `createClient` and need the same guarantee together with a health report
A connected bot can still have a stopped event subscription, the registration that delivers one event to its handler. A failed handler does not stop later events, and a full queue drops the oldest waiting event by default. A subscription registered with `overflow: "stop"` closes when its queue fills instead. A subscription the bot cannot work without is called a critical worker here. Check both the connection and each critical worker
## Watch the connection and subscription
This example answers `!ping` and stops the bot if its `messageCreate` subscription stops. It sets `overflow: "stop"`, so a burst the bot cannot keep up with counts as a failure instead of silently dropping messages. Health reports contain error types and counts, never event bodies or raw exceptions
```ts
import {
createClient,
type ClientDiagnostics,
type ConnectionState,
} from "@neontechspace/fluxerly";
export interface BotHealth {
readonly gateway: ConnectionState;
readonly criticalWorker: "starting" | "running" | "failed" | "stopped";
readonly handlerFailures: number;
}
export type SupervisedOutcome =
| { readonly kind: "stopped" }
| { readonly kind: "connection-failed"; readonly failure: string }
| { readonly kind: "critical-worker-failed"; readonly failure: string };
export async function runSupervisedBot(
token: string,
signal: AbortSignal,
reportHealth: (health: BotHealth, diagnostics: ClientDiagnostics) => void,
): Promise {
const client = createClient({ token });
let criticalWorker: BotHealth["criticalWorker"] = "starting";
let handlerFailures = 0;
const lifetimes: PromiseLike[] = [];
let outcome: SupervisedOutcome | undefined;
let primaryFailure: unknown;
let hasPrimaryFailure = false;
const localStop = new AbortController();
const report = () =>
reportHealth(
{ gateway: client.state, criticalWorker, handlerFailures },
client.diagnostics(),
);
const gatewayObserver = client.observeState(report);
try {
const registered = client.on(
"messageCreate",
async (message, handlerSignal) => {
if (message.author.isBot || message.content !== "!ping") return;
const reply = await client.messages.reply(message, "Pong!", {
signal: handlerSignal,
});
if (reply.isErr())
console.warn("Reply failed", { code: reply.error.code });
},
{
maxPendingMessages: 64,
overflow: "stop",
onError: (failure) => {
if (failure.kind === "handler") handlerFailures += 1;
if (failure.kind === "overflow") criticalWorker = "failed";
report();
},
},
);
criticalWorker = "running";
report();
const lifetime = AbortSignal.any([signal, localStop.signal]);
const connection = client.run({ signal: lifetime });
const observeConnection = new Promise<{
readonly source: "connection";
readonly result: Awaited;
}>(
(resolve, reject) =>
void connection.then(
(result) => resolve({ source: "connection", result }),
reject,
),
);
lifetimes.push(observeConnection);
const worker = registered.waitForClose({ signal: lifetime });
const observeWorker = new Promise<{
readonly source: "worker";
readonly result: Awaited;
}>(
(resolve, reject) =>
void worker.then(
(result) => resolve({ source: "worker", result }),
reject,
),
);
lifetimes.push(observeWorker);
const first = await Promise.race([observeConnection, observeWorker]);
const unexpectedWorkerStop =
first.source === "worker" &&
first.result.isOk() &&
!signal.aborted &&
client.state !== "Closing" &&
client.state !== "Closed";
if (
first.source === "worker" &&
first.result.isErr() &&
first.result.error._tag === "EventOverflowError"
) {
criticalWorker = "failed";
}
localStop.abort();
const [connectionResult, workerResult] = await Promise.all([
connection,
worker,
]);
if (criticalWorker === "failed" || unexpectedWorkerStop) {
criticalWorker = "failed";
report();
outcome = {
kind: "critical-worker-failed",
failure: unexpectedWorkerStop
? "CriticalWorkerStopped"
: "EventOverflowError",
};
} else {
criticalWorker = "stopped";
report();
if (
connectionResult.isErr() &&
connectionResult.error._tag !== "CancelledError"
) {
outcome = {
kind: "connection-failed",
failure: connectionResult.error._tag,
};
} else if (
workerResult.isErr() &&
workerResult.error._tag !== "CancelledError"
) {
outcome = {
kind: "critical-worker-failed",
failure: workerResult.error._tag,
};
} else {
outcome = { kind: "stopped" };
}
}
} catch (failure) {
primaryFailure = failure;
hasPrimaryFailure = true;
} finally {
localStop.abort();
const settled = await Promise.allSettled(lifetimes);
const rejected = settled.flatMap((result) =>
result.status === "rejected" &&
(!hasPrimaryFailure || result.reason !== primaryFailure)
? [result.reason]
: [],
);
try {
await client.shutdown();
} catch (failure) {
rejected.push(failure);
} finally {
gatewayObserver.close();
}
if (hasPrimaryFailure && rejected.length > 0) {
primaryFailure = new AggregateError(
[primaryFailure, ...rejected],
"Bot failed and cleanup also failed",
);
} else if (!hasPrimaryFailure && rejected.length === 1) {
primaryFailure = rejected[0];
hasPrimaryFailure = true;
} else if (!hasPrimaryFailure && rejected.length > 1) {
primaryFailure = new AggregateError(rejected, "Bot cleanup failed");
hasPrimaryFailure = true;
}
}
if (hasPrimaryFailure) throw primaryFailure;
return outcome!;
}
```
The health callback can feed a readiness endpoint or a process manager. The `diagnostics` snapshot describes gateway state, request pressure and local queues. It does not establish that a critical worker is alive, so the separate worker state remains necessary
The subscription's `onError` counts an isolated handler failure while the subscription continues. Because of `overflow: "stop"`, a full queue closes the subscription, changes the worker state to failed and makes `waitForClose` return `EventOverflowError`. The example then aborts `client.run()` and waits for the connection, worker and final cleanup
## Choose the application policy
If a process manager runs the bot, exit with a failure status after `critical-worker-failed` so it can start a new process. To restart within the same process, call `runSupervisedBot` again with a new client and a limit on restart attempts
A bot split across processes by the [supervisor](https://fluxerly.neontechspace.com/docs/sharding.md#run-shards-in-several-processes) gets the process-manager policy by default: When a child process exits unexpectedly, the parent starts a new one for the same shards, up to three times in a row. The parent's `workers.status()` also includes each child's latest `diagnostics` snapshot, so one place shows every child's gateway state and request pressure
A restart subscribes only to future events. It does not rerun the failed handler or recover events missed while the subscription was stopped. For work that must survive a restart, the application needs a durable queue, rules to prevent duplicate work and a way to check what already completed
Noncritical subscriptions can keep their existing isolated-failure policy. Their handler failure does not close this critical subscription or the client. If a noncritical worker must affect readiness, supervise its `waitForClose()` explicitly too
## Limit subscriptions created while the bot runs
Each SDK subscription and collector limits its own queue, but nothing caps how many subscriptions the client can have in total. Register workers at startup where possible
Budget workers created at runtime
Keep a reviewed list of workers registered at startup. If the application creates workers dynamically, route every such creation through one application-owned budget. Reserve capacity before registration and release it only after registration fails or the worker's `waitForClose()` and required cleanup finish. A wrapper cannot enforce the budget if other code can register directly, so restrict direct client access to code that applies the same budget
The `diagnostics.events` snapshot reports this client's open event sources, message collectors, reaction collectors and currently executing subscription callbacks. Use those payload-free counters to monitor usage and alert near the budget's limits. They are not enforced caps, process-memory measurements or counts of collector filters and arbitrary application tasks. The application's reservations determine whether another worker can register
## Drain application-owned work
Default handlers receive an `AbortSignal`, but the application must still track its own Promises, even when they respond to cancellation. Returning a Promise lets the SDK wait for that handler's work and report its failure. Closing a subscription does not wait for it, and neither does a plain `client.shutdown()`, which cancels running handlers at once
A shutdown can drain first. With `client.shutdown({ drainMs: 10_000 })`, the client stops accepting new events, lets running handlers, their waiting events, running [scheduled tasks](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#run-work-later-or-on-a-schedule) and REST requests finish for up to that many milliseconds, then cancels what is left. The `runBot` runner drains this way when asked to stop, for up to its `drainMs` option, 5,000 ms by default
In both APIs, a child of the [supervisor](https://fluxerly.neontechspace.com/docs/sharding.md#run-shards-in-several-processes) drains when the parent stops it, including an automatic move to a larger shard plan, for up to the supervisor's `shutdownTimeoutMs` minus one second, which is 4 seconds with the default of 5,000 ms. A child failure or loss of the parent's message channel stops running work without draining. The drain covers only work that handlers return and scheduled tasks, not detached Promises
Collector progress callbacks behave differently: Their completion waits for the returned callback work. Native Effect handlers use interruption and awaited scoped [finalizers](https://fluxerly.neontechspace.com/docs/glossary.md#finalizer), as shown in the [Effect application testing guide](https://fluxerly.neontechspace.com/docs/effect-application-testing.md)
When an external operation must finish before process exit, retain its Promise in an application-owned set. Remove it on either settlement path without creating an unobserved rejected Promise. Stop intake first, then inspect the outcomes of the retained work
```ts
import type { Client, Message, OperationSignal } from "@neontechspace/fluxerly";
export function installTrackedHandler(
client: Client,
handle: (message: Message, signal: OperationSignal) => Promise,
) {
const active = new Set>();
const registered = client.on("messageCreate", (message, signal) => {
const work = Promise.resolve().then(() => handle(message, signal));
active.add(work);
void work.then(() => active.delete(work), () => active.delete(work));
return work;
});
return {
subscription: registered,
async stopAndDrain() {
registered.close();
const failures: unknown[] = [];
try {
const closed = await registered.waitForClose();
if (closed.isErr()) failures.push(closed.error);
} catch (failure) {
failures.push(failure);
}
const pending = await Promise.allSettled([...active]);
for (const result of pending) {
if (result.status === "rejected") failures.push(result.reason);
}
if (failures.length) throw new AggregateError(failures, "Application work failed during drain");
},
};
}
```
The application calls `stopAndDrain()` outside the tracked handler to avoid joining itself. The returned function drains work still active after intake stops, not a history of earlier failures. The ordinary handler-error hook remains responsible for earlier failures
An operation that ignores cancellation can keep this drain pending. A chosen application deadline bounds waiting only if the underlying service also has a supported cancellation or recovery policy. A timeout alone cannot prove that an external write stopped or was rolled back
---
# Use the Fluxerly CLI
Generate a starter bot, check project setup offline, triage issues, build installation URLs and sync coding-agent rules
The `@neontechspace/fluxerly` package ships the `fluxerly` command for project setup, offline verification, agent-assisted triage, installation URL generation and coding-agent rules. Pass `--help` or `--version` to inspect available commands and the installed SDK version. Every subcommand accepts `--help` (`-h`) and `--flag=value` syntax, and `doctor` and `triage` run even on Node.js older than 26.13 so they report the Node.js version check cleanly instead of crashing on load
Run installed subcommands with `npx --no`, `pnpm exec` or `bunx --no-install` so the package manager executes the local package rather than downloading an unscoped `fluxerly` package from npm
## Generate a starter with init
Create a new JavaScript, TypeScript or Effect bot project without replacing existing files, then install dependencies:
```sh
npx @neontechspace/fluxerly init
```
Available options:
- `--template js|ts|effect`: Selects the JavaScript, TypeScript or Effect starter without prompting
- `--dir `: Writes the starter into ``, creating it if needed
- `--pm npm|pnpm|bun`: Selects the package manager instead of detecting the launcher
- `--no-install`: Skips package installation and prints the install commands instead
The [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) walks through the generated files, `.env` setup and first run
## Check setup offline with doctor
Verify Node.js version, ESM setup, `tsconfig.json` (including legacy `moduleResolution` settings such as `node`, `node10` or `classic`), TypeScript 7, `@types/node`, Effect peer range, local or monorepo-hoisted `node_modules` drift, forbidden `require()` or deep `/dist/` and `/src/` imports, `AGENTS.md` and tool rule freshness, `.gitignore` hygiene, `.env` token prefixes and POSIX `.env` permissions (`chmod 600 .env`) without printing secrets or contacting Fluxer:
```sh
npx --no fluxerly doctor
```
Available options:
- `--dir `: Targets a bot folder other than the current directory
- `--json`: Prints structured JSON check results (`schemaVersion`, `ok`, `summary`, `versions`, `checks`) for scripts or CI
- `--strict`: Exits non-zero when warnings or failures are found
## Investigate failures with triage
Gather redacted project facts, redacted `tsconfig.json` compiler options, safe proxy and `NODE_OPTIONS` hints, the pinned Fluxer server commit, static `doctor` checks, an automatic **Detected SDK codes** table matched from attached logs or traces, and Fluxerly's triage playbook to diagnose whether an issue comes from application code, Fluxer or the SDK:
```sh
npx --no fluxerly triage
```
Available options:
- `[problem]`: Optional short description of what failed
- `--agent antigravity|claude|codex|opencode|t3code|other`: Chooses which coding-agent CLI to start, or `other` for a harness-agnostic prompt
- `--model `: Passes a model identifier through to the chosen coding-agent CLI
- `--dir `: Targets a bot folder other than the current directory
- `--log `: Attaches a redacted, ANSI-stripped tail (up to 16 KB from a bounded read, symlink-checked to refuse credential files) of a local log file or standard input (`-`)
- `--run `: Runs `` once with `FLUXERLY_DEBUG=rest,gateway` and attaches redacted output
- `--timeout `: Sets the timeout for `--run` (for example `45s`, `60000` or `2m`, default 30 seconds)
- `--debug `: Overrides `FLUXERLY_DEBUG` categories used by `--run`
- `--print`: Prints the triage playbook and redacted context without launching an agent
- `--out `: Writes the redacted Markdown triage brief to a file (mode `0600` on POSIX, refusing credential-like targets) without launching an agent
- `--json`: Prints structured JSON triage facts, doctor checks and detected SDK codes
For manual diagnosis steps without an agent, see [troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md)
## Build an installation URL with invite
Generate a Fluxer bot installation URL offline from a decimal application ID, validating every permission name locally:
```sh
npx --no fluxerly invite 1234567890123456789 --permissions ViewChannel,SendMessages,ReadMessageHistory
```
Available options:
- `--permissions `: Accepts comma-separated permission names or a decimal bitfield
- `--instance `: Targets a self-hosted Fluxer instance origin instead of hosted Fluxer
See [create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md#3-invite-the-bot-to-a-community) for application setup and community authorization steps
## Sync coding-agent rules with agents
Add, refresh or verify Fluxerly's bundled rules for coding agents after installing or updating the SDK:
```sh
npx --no fluxerly agents
```
Available options:
- `--target agents|skill|cursor|claude|gemini|all`: Chooses which agent instruction files to write
- `--check`: Exits non-zero when `AGENTS.md` is missing or out of date
- `--print`: Prints the Fluxerly rules section without modifying files
---
# Add prefix commands to a bot
Register prefix commands, convert arguments, add guards and cooldowns, and generate help from the same definitions
A [prefix command](https://fluxerly.neontechspace.com/docs/glossary.md#prefix-command) is a message such as `!ping` or `!greet Maya`. Fluxerly's [command router](https://fluxerly.neontechspace.com/docs/glossary.md#command-router) reads the name after the configured prefix and calls the matching handler. It uses the bot's existing client and does not open another connection. The SDK has no slash commands, buttons or other interaction components, so every command is a message the bot reads
These examples extend [the starter bot](https://fluxerly.neontechspace.com/docs/quick-start.md). Add commands to its existing `commands.commands` object, or replace its `commands` option with an example below
## Register commands
Each key of `commands` becomes a command name. Names and aliases use ASCII letters, digits, `_` or `-` and start with a letter or digit, so `!помощь` cannot be a command. The `reply` helper accepts a string or full message content and replies to the incoming message
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
ping: {
description: "Check that the bot can reply",
execute: ({ reply }) => reply("Pong!"),
},
about: {
description: "Describe this bot",
execute: ({ reply }) => reply("Built with Fluxerly"),
},
},
},
})
```
Sending `!ping` now answers `Pong!`, and `!about` describes the bot. Returning the reply's [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) from `execute` is enough: If the reply fails, the router reports the failure with the command name without stopping other commands
When do command definitions fail?
An invalid definition, such as a duplicate name or an unknown argument type, throws `ConfigurationError` when `runBot` is called, before the bot connects.
A command failure happens later, when a matching message arrives. A handler that throws, rejects or returns an Err result has failed, and the router reports it to the `onError` hook, when one is set, or logs it in full at Error
Commands keep the order of the object's own string keys. Omit `arguments` to receive the raw `args` without conversion, and use `arguments: {}` when a command accepts no arguments. The `reply` helper also forwards the handler's cancellation `signal`, so stopping the bot cancels a pending reply
## Convert arguments before execution
The router converts the words after the command name into typed values before running it. By default it splits the text on whitespace and keeps quote characters, so `!greet "Ada Lovelace"` arrives as the two words `"Ada` and `Lovelace"`. The option `parse: commands.parseQuoted` opts in to quoting: Single or double quotes keep words together and are removed from the argument, and a backslash writes the next character literally
A double quote opens a span anywhere. A single quote opens one only at the start of a word and closes it unless a letter or digit follows, so an apostrophe inside a word, as in `!say don't`, stays literal, `'it's fine'` is `it's fine` and `'Yes', 'No'` is `Yes,` and `No`
A word that begins with an apostrophe, such as `'twas`, opens a span, so write `\'twas`. This bot uses it to accept `!greet "Ada Lovelace"` and `!remind 10m Stretch`
```ts
import { commands, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
parse: commands.parseQuoted,
commands: {
greet: {
description: "Greet a name",
arguments: { name: { type: "text" } },
execute: ({ values, reply }) => reply(`Hello, ${values.name}!`),
},
remind: {
description: "Repeat a note after a delay",
arguments: {
delay: { type: "duration", min: 1_000, max: 3_600_000 },
note: { type: "text", rest: true },
},
execute: ({ client, message, values, reply }) => {
client.schedule((signal) => client.messages.reply(message, values.note, { signal }), {
delayMs: values.delay,
})
return reply("Reminder set")
},
},
},
},
})
```
The `remind` command hands the wait to [`client.schedule`](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#run-work-later-or-on-a-schedule), so it finishes at once instead of keeping a command slot busy, and the note arrives later as a reply. The bot owns the reminder, so stopping the bot cancels it, and a failed reply goes to the client-level `onError` or the log
In TypeScript, `values.name` is a string and `values.delay` is a number of milliseconds. A missing, invalid or extra argument stops the command before `execute`, and `runBot` answers with the reason and the command's usage, such as `Missing name. Usage: !greet `. That reply is the `onReject: "reply"` default of `runBot`. Set `onReject: "silent"` to send nothing, or pass a function for custom feedback. A router from `commands.create` gives no feedback unless `onReject` is set
An argument with `optional: true` may be left out. For example, `name: { type: "text", optional: true }` accepts `!greet` without a name, giving `values.name` the value `undefined`. The reply can use `values.name ?? "there"` for a fallback
Required arguments must come before optional ones, and an argument with `rest: true` must be last. A `text`, `integer`, `number`, `duration`, `boolean`, `choice` or `custom` argument with a `default` may also be left out, and produces that default instead of `undefined`
A `duration` argument reads text such as `90s`, `5m` or `1h30m` and produces milliseconds. Add `wholeSeconds: true` to reject a millisecond part such as `1m500ms`, for a value that must be whole seconds, like the `durationMs` of a [ban](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#moderate-members). Its `default`, when given, must then be whole seconds too
Other argument types include:
- Whole and decimal numbers, with `integer` and `number` and optional `min`, `max` and `default`
- Exact `true` or `false` flags, with `boolean` and optional `default`
- One of a fixed list of strings, with `choice` and optional `caseInsensitive` and `default`
- A decimal [ID](https://fluxerly.neontechspace.com/docs/glossary.md#id), with `id`. Add `mention: "user"`, `"channel"` or `"role"` to also accept that kind of mention, as in `{ type: "id", mention: "user" }`. The value is the ID either way
- A member of the message's [community](https://fluxerly.neontechspace.com/docs/glossary.md#guild), with `member`, which turns a user ID or mention into a `{ guildId, userId }` reference
- One entry from a fixed list of candidates given at registration, with `userChoice`, `channelChoice` or `roleChoice`. For any user, channel or role, use `id` or `member` instead
- Any other format, with `custom`, a synchronous parse function and optional `default`
Accepting an ID does not mean the user may act on that resource
To convert a single word outside a command, such as a button label or a stored setting, `commands.parseArgument("5m", { type: "duration" })` applies a built-in descriptor with the same rules as the router. It returns `undefined` for a rejected word and the descriptor's `default` for a missing one. A `member` descriptor also needs `{ guildId }` as its third parameter. For a custom descriptor, call its parse function directly
How are ID and member arguments checked?
An `id` or `member` argument accepts a nonzero decimal ID without leading zeroes, up to `9223372036854775807`, and the same limit applies to IDs inside mentions. Any other value is rejected as invalid before the command runs. Use a `custom` argument for other formats.
A `member` argument produces a `{ guildId, userId }` reference in the message's community without checking that the user is still a member
## Reply to messages that do not run a command
A message that starts with the prefix but runs no command is ignored by default. Pass `onUnmatched` to tell the sender why. Its second parameter names the cause in `_tag`:
- `CommandUnknownName` for a name that is not registered. Its `suggestion` names the closest registered command when one is similar
- `CommandMissingSubcommand` for a group such as `admin` typed without a subcommand. Its `path` names the group
- `CommandParserRejected` when the parser could not read the text. With `commands.parseQuoted`, its `reason` explains a quote that never closes or a backslash at the end. When the open span held a single quote followed by a letter or digit, as in `'a'b` or `'it's`, the `reason` also says that such a quote may have been meant to close the span, so a space after it or double quotes fix the input. The `reason` is absent when the text is not a command at all, such as `!` alone. Its `name` holds the command name the parser read, as typed, so a reply can say which command the mistake was for
This bot answers a syntax mistake with the parser's own explanation. Without the callback, `!greet "Ada` is ignored
```ts
import { commands, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
parse: commands.parseQuoted,
onUnmatched: ({ reply }, unmatched) => {
if (unmatched._tag !== "CommandParserRejected" || unmatched.reason === undefined) return undefined
return reply(unmatched.reason)
},
commands: {
greet: {
arguments: { name: { type: "text" } },
execute: ({ values, reply }) => reply(`Hello, ${values.name}!`),
},
},
},
})
```
The router never replies to these messages by itself. The callback runs for every one of them and anyone can cause that, so an application that replies should limit how often. A channel may also hold other bots with the same prefix, so reply to an unknown name or a syntax mistake only when this bot should answer for that prefix
A custom `parse` function can give its own explanation by returning `{ reason: "Separate the words with spaces" }` instead of `undefined`. The reason reaches `onUnmatched` unchanged, so it should be fixed text that leaves the sender's input out
To suggest a name in a reply of the application's own, `commands.suggest("pnig", ["ping", "help"])` applies the rule behind `suggestion` to any list of names and returns `"ping"`. Pass only names that may be revealed, because the helper does not know which commands are hidden
Each unmatched message is also logged at Debug with the code `commands.unmatched` and the fields `reason`, `messageId`, `channelId` and, when there is one, `suggestion`. The `reason` field holds the `_tag`, and for a rejected parse the log message ends with the parser's explanation
## Guard, limit and wrap commands
A [guard](https://fluxerly.neontechspace.com/docs/glossary.md#guard) decides whether a matched command may run. A [cooldown](https://fluxerly.neontechspace.com/docs/glossary.md#cooldown) limits how often each user, channel or community can run it. [Middleware](https://fluxerly.neontechspace.com/docs/glossary.md#middleware) wraps every command, for example to measure how long it takes
```ts
import { guards, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
mentionPrefix: true,
use: [
async (context, next) => {
const started = Date.now()
await next()
console.info(`${context.name} took ${Date.now() - started} ms`)
},
],
commands: {
purge: {
description: "Delete recent messages",
guard: [guards.guildOnly(), guards.requirePermissions(["ManageMessages"])],
cooldown: { durationMs: 30_000, per: "channel" },
arguments: { count: { type: "integer", min: 1, max: 100, default: 10 } },
execute: ({ values, reply }) => reply(`Would delete ${values.count} messages`),
},
},
},
})
```
Here `!purge` runs only in a community, for a member with the Manage Messages permission, and at most once every 30 seconds in each channel. With `mentionPrefix`, a mention of the bot also works as a prefix
Only messages a person typed can run commands. Messages from bots are skipped by default, and the notices Fluxer posts with text of its own never run commands. For example, a thread named `!ping` makes Fluxer post a notice containing that name, and it does not run `!ping`
A guard returns `true` to allow the command, `false` to deny it without an automatic reply or `{ deny: "reason" }` to deny it with a reason that `onReject: "reply"` sends. A false verdict stays silent even with the `runBot` reply default, but still counts as a rejection, logs `commands.rejected` at Debug and reaches a custom `onReject` callback. Each built-in guard denies with a specific reason and covers one common check, allowing only:
- Messages sent in a community, with `guards.guildOnly()`
- Direct and group conversations, with `guards.dmOnly()`
- The owner of the bot's application, with `guards.ownerOnly()`
- Listed user IDs, with `guards.ownerOnly(ids)`
- Members who have every named permission in the channel, with `guards.requirePermissions(names)`
How the built-in guards read data
The `requirePermissions` guard decides with `permissions.fetch` and `preferCache`: It reads the community, member, roles and channel from enabled caches first and fetches only what is missing, at most once each per command. Cached values follow the gateway events applied so far, so check again with a fresh `permissions.fetch` before an action where a stale grant matters
The denial names each missing permission by Fluxer's label, such as `Manage community`. In a thread, it also reads the parent channel the same way and decides from the parent's permissions as Fluxer does, with `SendMessages` granted exactly when `SendMessagesInThreads` is. A failed read fails the command, which is reported with the command name
When Fluxer sent the channel without its permission overwrite list, the guard denies the command because it cannot confirm the channel's permissions. Its decision does not guarantee that Fluxer allows a later action
The `dmOnly` guard denies a message that has a `guildId` without a request. Otherwise it confirms a private conversation from the direct-message cache or the channel cache, or reads the channel once. A cached or fetched community channel denies the command. A read that fails for any other reason, such as a network failure or timeout, leaves the channel unconfirmed and fails the command, which is reported with the command name
Enable `cache.directMessages` to avoid a read for each command in the same conversation
The `ownerOnly()` guard reads the application's owner from Fluxer on the first command and keeps it for the client's lifetime. A failed read fails the command, and the next command reads again
How cooldowns are stored
A cooldown takes `durationMs` and `per`, which is `"user"` by default, `"channel"` or `"guild"`. Without a `store`, the router keeps cooldowns in memory in this process. That store holds 10,000 keys by default. Set the router's `cooldowns: { maxEntries }` option to change the limit, for example `cooldowns: { maxEntries: 50_000 }`
A full store never turns a user away: It removes expired keys first, then the key that would expire soonest, which lets that key run again early. Pass a `store` to share cooldowns between processes
How often a rejected command is answered
So that repeated attempts do not make the bot repeat itself, the `"reply"` feedback answers an active cooldown once until it expires, and a guard denial with a reason once per user and command every 5 seconds. A guard returning `false` sends nothing. Argument errors are answered every time.
A skipped answer still counts as a rejection and is logged at Debug. An `onReject` function receives every rejection instead, so it can apply its own limit
### Answer in another language
The built-in answers are in English. To answer in another language, pass a function as `onReject` and read the rejection's `_tag`:
```ts
import { runBot, type PrefixCommandRejection } from "@neontechspace/fluxerly"
function inGerman(rejection: PrefixCommandRejection): string | undefined {
switch (rejection._tag) {
case "CommandArgumentRejected":
return rejection.reason === "Missing" ? `Es fehlt: ${rejection.argument}` : `Ungültig: ${rejection.argument}`
case "CommandCooldownActive":
return `Bitte noch ${Math.ceil((rejection.retryAtMs - Date.now()) / 1000)} Sekunden warten`
case "CommandGuardRejected":
return rejection.reason
}
}
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
onReject: ({ reply }, rejection) => {
const text = inGerman(rejection)
return text ? reply(text) : undefined
},
commands: {
ping: { description: "Check that the bot can reply", execute: ({ reply }) => reply("Pong!") },
},
},
})
```
The function runs for every rejection, so a user who keeps trying during a cooldown gets an answer each time
## Control how commands run
By default `runBot` runs up to eight commands at a time, and when more messages wait than the queue holds, it drops the oldest waiting message with a Warn record. The `commands` option also accepts the delivery settings of an event handler, `concurrency`, `partition`, `partitionReady`, `overflow`, `maxPendingMessages` and `maxPendingBytes`, and passes them to the router unchanged
Invalid values throw `ConfigurationError` when `runBot` is called. This bot runs the commands of each channel one at a time in the order they arrived, and stops instead of dropping commands when 64 messages are waiting
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
partition: "channel",
maxPendingMessages: 64,
overflow: "stop",
commands: {
ping: { execute: ({ reply }) => reply("Pong!") },
},
},
})
```
With `overflow: "stop"`, a full queue stops the bot with `CriticalWorkerStoppedError`, which names the `messageCreate` subscription and the limit it exceeded. Leave `overflow` unset to keep the bot running and drop waiting messages instead. With a `partition`, the drops come from the longest backlog, as the [events guide](https://fluxerly.neontechspace.com/docs/events-and-collectors.md) describes
A partition can need its own setup before its commands run. With `partitionReady`, the SDK calls the hook with the key before the first waiting message of that key starts, and the key's messages wait in the queue, using no command slot, until the returned promise settles. Other keys keep running meanwhile. The hook needs `partition` and otherwise `runBot` throws `ConfigurationError`
A hook that throws, rejects or returns an `Err` result reports each waiting message of that key to the `onError` of the commands when they have one, otherwise to the client-level `onError` or the log, like a throwing `partition` function and an overflow that stops the router, and those messages run no command. The [events guide](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#wait-for-a-communitys-setup) covers the timing rules, which are the same for commands
```ts
import { runBot } from "@neontechspace/fluxerly"
export function pingAfterSetup(setups: Map>) {
return runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
partition: "guild",
// A direct message has no community and is keyed by its channel, so an unknown key counts as ready
partitionReady: (key) => setups.get(key),
commands: {
ping: { execute: ({ reply }) => reply("Pong!") },
},
},
})
}
```
## Use the Effect entry point
The [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect) API accepts the same options, with `partitionReady` returning an Effect whose required services become requirements of the program. Each reply stops when the command handler is interrupted and keeps `SendError` in the Effect error channel. Services required by any command remain requirements of the returned program
```ts
import { Effect } from "effect"
import { runBot } from "@neontechspace/fluxerly/effect"
export const program = runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
ping: { execute: ({ reply }) => reply("Pong!").pipe(Effect.asVoid) },
about: { execute: ({ reply }) => reply("Built with Fluxerly").pipe(Effect.asVoid) },
},
},
})
```
## Attach commands to an existing client
To add commands to a client the application already manages, create a router, register commands and attach it to the client. Creation and registration throw `ConfigurationError` for invalid definitions. Close the returned subscription to detach the router, or wait for its cleanup with `waitForClose()`. The second argument of `attach` takes the same delivery settings as `runBot`, including `partitionReady`
```ts
import { commands, type Client } from "@neontechspace/fluxerly"
export function attachCommands(client: Client) {
return commands
.create({ prefix: "!" })
.registerMany({
ping: { execute: ({ reply }) => reply("Pong!") },
about: { execute: ({ reply }) => reply("Built with Fluxerly") },
})
.attach(client)
}
```
## Add help from the registered commands
Each command receives a `help` function that builds help pages from the registered descriptions and arguments, and a `sendHelp` function that sends them
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
help: {
description: "List the commands",
execute: ({ sendHelp }) => sendHelp(),
},
ping: {
description: "Check that the bot can reply",
execute: ({ reply }) => reply("Pong!"),
},
},
},
})
```
Sending `!help` lists each command with its description. Each page holds up to 2,000 characters, which fits one message. The `sendHelp` function sends a single page as a plain message, and several pages as reaction pages that the command's author flips with ◀ and ▶. The `help` function only builds the pages, for a bot that sends them its own way. A router created with `commands.create` has the same `help` method
The `paginate` function shows any list of pages the same way, as in `({ paginate }) => paginate(["Rules 1 to 5", "Rules 6 to 10"])`. Adding or removing an arrow turns the page, so the bot needs only Add Reactions and Read Message History. The pages stop listening after 60 seconds without a click or 5 minutes in total, and the bot then removes its arrows. Pass `users` to let other people flip them. [Reaction pages](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#show-pages-with-reactions) explains the options
A command that returns or awaits `sendHelp()` or `paginate()` with several pages stays active until listening ends. Eight open sessions can fill the router's default command slots, making later commands wait. With `partition: "channel"`, one session makes later commands in that channel wait
For independent page sessions, build the pages with `help()` and send them through `client.messages.paginate` in a [scheduled task](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#run-work-later-or-on-a-schedule). A failure then goes to the client's `onError` or the log
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
help: {
description: "List the commands",
execute: ({ client, message, help }) => {
const pages = help()
client.schedule((signal) =>
client.messages.paginate(message.channelId, pages, {
users: [message.author.id],
signal,
}),
)
},
},
},
},
})
```
To keep a command out of help and out of unknown-command suggestions, for example an owner-only tool, register it with `hidden: true`. Hidden commands still run when someone types their name, so hiding does not restrict access. Protect each command that needs it with a guard
For a larger bot, split command definitions by feature and attach one combined router. [Groups](https://fluxerly.neontechspace.com/docs/api/js-ts/commands/#prefixcommandrouter) such as `admin` in `!admin inspect` add structure when needed. The `group` option of `help`, such as `help({ group: ["admin"] })`, describes one group. A group registered with `hidden: true` hides everything inside it, and selecting a hidden group throws `ConfigurationError` as for a missing one
## Wire it up
A complete bot places the router beside the other `runBot` options. This one adds a help command, a per-user cooldown, a larger cooldown store, its own failure hook and a hidden owner-only command
```ts
import { guards, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
cooldowns: { maxEntries: 50_000 },
onError: (report) => console.error(report.describe()),
commands: {
help: {
description: "List the commands",
execute: ({ sendHelp }) => sendHelp(),
},
ping: {
description: "Check that the bot can reply",
cooldown: { durationMs: 5_000, per: "user" },
execute: ({ reply }) => reply("Pong!"),
},
uptime: {
hidden: true,
guard: guards.ownerOnly(),
execute: ({ reply }) => reply(`Running for ${Math.round(process.uptime())} s`),
},
},
},
})
```
The `ownerOnly()` guard allows only the owner of the bot's application, as Fluxer reports it, so the owner's ID needs no configuration. The commands `onError` hook receives command failures instead of the client-level `onError`, and without either hook the SDK logs each failure in full. If the bot itself stops with a failure, such as a rejected token, `runBot` logs it once and sets `process.exitCode` to 1
---
# Configure a bot
Choose the token, events, logging, cache, gateway and connection options for a bot
A bot is configured with one options object passed to [`runBot`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#runbot). The same client options also work with [`createClient`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#createclient) when an application manages the client itself. Only `token` is required. Every other option has a default that suits a small bot, so add options when the bot needs them
## A typical production configuration
This bot reads its token from the environment, stops cleanly on SIGTERM, prints JSON log lines, keeps the community data that permission checks need in memory and asks Fluxer to skip events it does not use
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
logging: { format: "json" },
cache: {
guilds: true,
channels: true,
roles: true,
members: { maxEntries: 5_000 },
messages: { maxEntries: 2_000, maxAgeMs: 60 * 60 * 1_000 },
},
gateway: {
ignoredEvents: "auto",
presence: { status: "online", customStatus: { text: "Type !ping" } },
},
rest: { defaultTimeoutMs: 15_000 },
commands: {
prefix: "!",
commands: {
ping: {
description: "Check that the bot replies",
execute: ({ reply }) => reply("Pong!"),
},
},
},
})
```
Invalid options throw `ConfigurationError` from `runBot` before anything connects. If the other options are valid, a missing or empty token instead returns an Err containing `ConfigurationError` and is reported as a failed run. The error identifies the invalid setting. A misspelled option name gets a suggestion when it is close enough to a known name
A failure that stops the running bot, such as a rejected token, is logged once and sets `process.exitCode` to 1, so the process ends with a failure status. Set `reportFailure: false` only when the application handles the returned [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) and the exit status itself
## Options at a glance
| Option | What it controls |
| --- | --- |
| [`token`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-token) | The bot token. Pass `process.env.FLUXER_BOT_TOKEN` directly: An unset variable fails with a hint that points at it |
| [`events`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-events) | One [handler](https://fluxerly.neontechspace.com/docs/glossary.md#handler) per event name, as a function or an object with its own delivery settings |
| [`commands`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-commands) | Prefix commands, guards and cooldowns, as described in [commands](https://fluxerly.neontechspace.com/docs/commands.md) |
| [`setup`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-setup) | Startup work that runs after handlers are registered and before the bot connects |
| [`onError`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-onerror) | Receives handler, command and callback failures. Without it, each failure is logged in full at Error |
| [`ignoreBots`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-ignorebots) | Skips messages written by bots, including the bot's own, before they reach handlers and commands. On by default |
| [`processSignals`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-processsignals) | Stops the bot cleanly on Ctrl+C (SIGINT) and SIGTERM. On by default, and set `false` to leave these signals to the application |
| [`signal`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-signal) | An `AbortSignal` that stops the bot from application code |
| [`reportFailure`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-reportfailure) | Whether a failed run is logged and sets `process.exitCode`. On by default |
| [`logging`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-logging) | Level, per-category levels, output format and custom sinks. See [logging](https://fluxerly.neontechspace.com/docs/logging.md) |
| [`cache`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-cache) | Which resources the client keeps in memory for local lookups. Nothing is cached by default. See [history and cache](https://fluxerly.neontechspace.com/docs/history-and-cache.md) |
| [`gateway`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-gateway) | Events Fluxer should not send, session flags, the initial presence and what to do with malformed events |
| [`sharding`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-sharding) | Split the bot across several gateway connections, called [shards](https://fluxerly.neontechspace.com/docs/glossary.md#shard). See [sharding](https://fluxerly.neontechspace.com/docs/sharding.md) |
| [`connection`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-connection) | Startup deadline, startup attempts and reconnect timing |
| [`rest`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-rest) | How many HTTP requests run and wait at once, and the default request deadline |
| [`transport`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-transport) | Replace the HTTP and WebSocket implementations or the User-Agent, for proxies, instrumentation and tests |
| [`instance`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-instance) | Connect to a self-hosted Fluxer instance instead of hosted Fluxer |
| [`messageFields`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-messagefields) | Build only the message fields the bot reads |
| [`uploads`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-uploads) | The byte budget reserved by queued and active attachment uploads |
The reference for [`BotOptions`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions) lists every nested setting with its default and allowed range
## Token
Keep the token out of source files and images. Read it from an environment variable and start the bot with `node --env-file=.env bot.js` during development, or let the process manager set the variable in production, as shown in [deploying](https://fluxerly.neontechspace.com/docs/deploying.md). The SDK never writes the token to logs or error messages
The SDK removes surrounding spaces and one pair of matching quotes, which `.env` files often add. It adds the `Bot` scheme itself, so a token that starts with `Bot ` or `Bearer ` is rejected with `ConfigurationError`
## Events and the gateway
Fluxer's [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) has no [intents](https://fluxerly.neontechspace.com/docs/glossary.md#intent) setting to request. Fluxer filters events by permissions, visibility, subscriptions and shard, and `gateway.ignoredEvents` removes more. Register handlers for the events the bot is allowed and subscribed to receive. Presence updates for chosen members need [`presence.setMembers`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#presence-setmembers)
Setting `ignoredEvents: "auto"` asks Fluxer to skip supported event types that no registered handler, enabled cache or SDK feature needs, which saves bandwidth and decoding on busy bots. The list is computed when the bot connects, so register handlers before that, as `runBot` does
Limits of automatic event filtering
A handler registered after the bot connected receives the skipped types only after that shard starts a new session. A connection that resumes its session keeps the old list. A `raw` event subscriber turns automatic filtering off
Enabled cache categories keep the event types they need, so large caches reduce the savings. Fluxer still delivers a message that mentions the bot, @here or @everyone. An explicit array of upper-case dispatch names, such as `["TYPING_START"]`, is also accepted. The [`GatewayOptions`](https://fluxerly.neontechspace.com/docs/api/js-ts/options/#gatewayoptions) reference lists the names that cannot be skipped
Each event handler has a small queue. By default `messageCreate` runs up to eight handlers at a time and other events one at a time, and a full queue drops the oldest waiting event with a Warn record instead of stopping the bot
Pass `{ handler, concurrency, maxPendingMessages, maxPendingBytes, overflow }` instead of a function to change this for one event. The `overflow` setting is `"dropOldest"` by default, `"dropNewest"` to drop the arriving event instead, or `"stop"` to close that handler's subscription. See [bot lifetime](https://fluxerly.neontechspace.com/docs/starter-lifetime.md) for how the runner treats handlers
Running several handlers at a time can finish events out of order. The `partition` setting keeps related events in order: With `partition: "channel"`, the messages of one channel run one after another while other channels run beside them, and `partition: "guild"` does the same for each community, which the API calls a guild. A partitioned handler runs up to eight events at a time unless `concurrency` says otherwise
A partitioned handler can also hold a key's events until that key is ready, with `partitionReady`, which takes the key and returns a promise or Effect. See the [events guide](https://fluxerly.neontechspace.com/docs/events-and-collectors.md) for the hook and for how a full partitioned queue drops events from the longest backlog
## Logging and errors
The client prints startup, readiness, lost connections, long rate-limit waits, shutdown and every application error by default. Set `logging.level` or per-category levels to change what appears, and `logging.sink` to forward records to an existing logger. Set the `FLUXERLY_DEBUG` environment variable to turn on Debug records without changing code. The [logging guide](https://fluxerly.neontechspace.com/docs/logging.md) shows the output and every setting
Pass `onError` to send handler and command failures to an error tracker. Each [`FailureReport`](https://fluxerly.neontechspace.com/docs/api/js-ts/logging-and-diagnostics/#failurereport) holds the original error and the IDs involved, and `report.describe()` returns readable text. See [reliability](https://fluxerly.neontechspace.com/docs/reliability.md) for failures that do return a Result
## Cache
The client keeps no [cache](https://fluxerly.neontechspace.com/docs/glossary.md#cache) unless asked. Enable a category with `true`, or pass `{ maxEntries, maxBytes, maxAgeMs }` to bound it. The `maxAgeMs` setting also accepts a function that receives each snapshot and returns its age limit, `null` for no limit or `0` to skip keeping it, so a category can keep only what the bot needs
Caching communities, channels, roles and members lets permission checks such as `guards.requirePermissions` answer without extra requests. Enabled community, role, channel, emoji and sticker caches fill from the community data Fluxer sends when the bot connects. The [history and cache guide](https://fluxerly.neontechspace.com/docs/history-and-cache.md) explains what a cached value can and cannot prove
Each category keeps at most 1,000 entries and 4 MiB by default, and messages 1,000 entries and 8 MiB. The limits apply to the whole client, not per community. When a category is full, its least recently used entry is removed, so lookups start to miss. Size each category for the communities this process serves:
- Communities (`guilds`): At least the number of communities
- Roles and channels: About the number of communities times the average roles or channels per community
- Members: The members the bot actually looks up, such as recently active users, not every member
Under a [supervisor](https://fluxerly.neontechspace.com/docs/glossary.md#supervisor), each child process sizes its caches for its own shards. This helper logs how full each enabled category is
```ts
import type { Client } from "@neontechspace/fluxerly"
export function logCacheUsage(client: Client) {
for (const [kind, cache] of Object.entries(client.diagnostics().caches)) {
if (!cache.configured) continue
console.info(
`${kind}: ${cache.retainedEntries} of ${cache.maxEntries} entries, ${cache.accountedBytes} of ${cache.maxBytes} bytes`,
)
}
}
```
When cached entries are cleared
After a lost connection, community, member, role, channel, emoji and sticker entries stay when the session resumes, except cached threads, which are removed. These entries are cleared when the shard has to start a new session. A shard's first session clears them too, so entries read before connecting do not outlast the first READY
A lost connection clears the message, user and direct-message entries it could have changed, even when the session resumes. A process that resumes a session saved before a restart refills the community, role and channel caches through REST once every shard is ready, unless `sharding.refillCaches` is `false`. Byte counts measure the stored JSON, not process memory
## Connection and requests
The defaults suit most bots: Startup may take 30 seconds with up to 3 attempts per [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard). A process with several shards starts them one second apart and adds that second to the deadline for each shard after the first. When Fluxer rate-limits instance discovery with a wait, startup waits at least that long and tries again without using up an attempt, until the startup deadline. Discovery sends no further request during the wait
The first Identify extends the startup deadline once by 25 seconds, because Fluxer may take that long to start a session while its Identify queue is busy. A reconnection attempt gets 30 seconds, plus 25 when it sends Identify instead of resuming. Setting `startupTimeoutMs` or `recovery.attemptTimeoutMs` makes that value one fixed deadline that Identify does not extend
After that, a lost connection is retried with a growing random delay, capped at 30 seconds unless Fluxer asks for a longer wait, and transient failures never make the bot give up. The `connection` option changes those values
The `rest` option sets how many API requests run at once (by default 4 for each shard, up to 64), how many may wait (default 256) and the default deadline for each request (30 seconds). When the queue is full, a new request fails with reason `busy` and the SDK logs `rest.busy` at Warn. Raising `rest.concurrency` does not raise Fluxer's [rate limits](https://fluxerly.neontechspace.com/docs/glossary.md#rate-limit), which still apply per route
The `transport` option is for advanced cases, such as sending traffic through a proxy or recording requests. The [testing entry point](https://fluxerly.neontechspace.com/docs/testing.md) uses it to connect a real client to an in-memory Fluxer
## Effect configuration
The [Effect `runBot`](https://fluxerly.neontechspace.com/docs/api/effect/client-and-lifecycle/#runbot) accepts the same options, with Effect handlers and an Effect `setup`. The Effect API also accepts a `connection.recovery.schedule` that decides reconnect delays. See the [Effect first bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md) guide
---
# Core concepts
Understand clients, events, results, caches and the gateway before building further
A few ideas explain most of how Fluxerly works. This page introduces each one briefly and points to the guide that covers it in depth. The [glossary](https://fluxerly.neontechspace.com/docs/glossary.md) defines the remaining terms
## Gateway and REST
A bot talks to Fluxer in two ways:
- The [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) is a connection that stays open while the bot runs. Fluxer pushes events through it, such as a new message or a member joining
- [REST](https://fluxerly.neontechspace.com/docs/glossary.md#rest) requests are single HTTP calls that read or change something, such as sending a message or fetching a channel
Receiving events needs the gateway. Sending a message or reading data does not, so a script that only posts one message can skip connecting
A route or event without a named method still works, as [raw requests and raw events](https://fluxerly.neontechspace.com/docs/raw-requests-and-events.md) shows
Outgoing gateway commands and presence
Most outgoing work uses the SDK's named methods. The `gateway.send` method is an escape hatch for a command without one. Outgoing status, member subscriptions, count requests and custom commands share a pacing budget, so a command can wait locally before reaching the socket. An excess custom-command submission fails with reason `busy` when its waiting queue is full. Cancelling an unsent custom command immediately frees its place, and disconnecting abandons it rather than replaying it on the next connection
The `presence.set` method retains the latest requested status for each ready local shard. Changes replace an unsent update instead of building a backlog. The four-second spacing starts when the update reaches the socket, not when it enters the queue. The `presence.setMembers` method follows the same latest-intent rule for an unsent member selection, and clearing it withdraws the queued request
The `guilds.fetchCounts`, `channels.fetchMemberCounts` and `members.iterateChunks` methods require a ready gateway and share a separate request-slot budget. Their deadlines include gateway pacing waits. Cancellation or deadline expiry withdraws unsent commands and releases local capacity, but cannot stop work already sent to Fluxer
Fluxer accepts 12 member requests per account in 10 seconds and drops the rest without an answer. The `members.iterateChunks` helper refuses a request that would exceed 12 in 11 seconds, with reason `rateLimit` and a `retryAfterMs` wait instead of timing out. A member request sent with `gateway.send` counts as well, but `gateway.send` never refuses one. The children of one [supervisor](https://fluxerly.neontechspace.com/docs/sharding.md#run-shards-in-several-processes) share this count, while other processes with the same token are not counted
## The client
A client holds the token, the connection and everything the bot has registered. There are two ways to get one:
- The `runBot` function creates a client from one options object, registers event handlers and commands, connects and keeps running until the bot stops. Most bots need only this, as the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) and [small bot](https://fluxerly.neontechspace.com/docs/small-bot.md) show
- The `createClient` function returns a client without connecting it. Use it for scripts that only send requests, or when the application must control connecting, running and stopping itself
Invalid settings throw a `ConfigurationError` right away, before anything connects. A misspelled option name comes with a suggestion, such as `Did you mean "processSignals"?`. A missing token is reported instead: The `runBot` function logs it with a hint, sets exit code 1 and returns the error
## Events and handlers
An [event](https://fluxerly.neontechspace.com/docs/glossary.md#event) is something Fluxer reports through the gateway, such as `messageCreate` or `guildMemberAdd`. A [handler](https://fluxerly.neontechspace.com/docs/glossary.md#handler) is the function that runs for it. With `runBot`, handlers go in the `events` option, and prefix commands in the `commands` option. A [guild](https://fluxerly.neontechspace.com/docs/glossary.md#guild) in the API is a community in Fluxer, so `guildMemberAdd` reports a member joining a community
There is no ready event. The `runBot` function logs a line when the bot is connected, and its `setup` option runs startup work before the bot connects. To run code after that, see [Run code once the bot is connected](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#run-code-once-the-bot-is-connected). With `createClient`, a successful `client.connect()` Result confirms that the bot is connected
Handler failures are isolated. A failing handler is reported to `onError`, or logged when there is no `onError`, and the bot keeps running. Each handler also receives a cancellation `signal`, which the SDK triggers when the bot stops. The [events guide](https://fluxerly.neontechspace.com/docs/events-and-collectors.md) covers waiting for replies and handling bursts
## Results
Expected request failures, such as a rejected message send, are returned rather than thrown. Default API requests return a [ResultAsync](https://fluxerly.neontechspace.com/docs/glossary.md#resultasync), which becomes a [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) when awaited. A Result is either a success with a `value` or a failure with an `error`:
- Check `isErr()` when the code should handle a failure itself, for example by replying with an explanation
- Wrap the call in `orThrow(...)` when a failure should end the current function. It returns the value, or throws the error
- Return the Result from a handler or command to let the SDK report a failure to `onError`
Every SDK error has a stable `code`, a readable message and often a `hint`. Printing it with `describeError(error)` shows all of that and the chain of causes, with recognized credentials masked. The [error and log codes](https://fluxerly.neontechspace.com/docs/codes/) page lists every code. The [reliability guide](https://fluxerly.neontechspace.com/docs/reliability.md) explains which failures are safe to retry
## Caches
A [cache](https://fluxerly.neontechspace.com/docs/glossary.md#cache) keeps local copies of what Fluxer has sent, such as channels, members or messages. Caches are off unless enabled with the client's `cache` option, and each kind of data is switched on separately
A cache lookup and a remote read look similar but behave differently:
```ts
import { orThrow, type Client } from "@neontechspace/fluxerly"
export async function channelName(client: Client, channelId: string) {
// A local snapshot: instant, but it can be missing or out of date
const cached = client.channels.get(channelId)
if (cached !== undefined) return cached.name
// A REST read: current when it is read, but it takes a request and can fail
const channel = await orThrow(client.channels.fetch(channelId))
return channel.name
}
```
Use `get` when a recent copy is good enough, and `fetch` when the answer must be current. The [cache settings](https://fluxerly.neontechspace.com/docs/configuration.md#cache) turn on and bound each cache category, and the [history and cache guide](https://fluxerly.neontechspace.com/docs/history-and-cache.md) shows the message cache in use
## Effect API
Fluxerly has two entry points with the same features. The default one, `@neontechspace/fluxerly`, uses `async` functions and Results and works in JavaScript and TypeScript. The native one, `@neontechspace/fluxerly/effect`, returns [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect) values for applications built with the Effect library, where failures, cancellation and cleanup are part of each value's type
Choose the default API unless the application already uses Effect. The [Effect learning path](https://fluxerly.neontechspace.com/docs/effect-first-bot.md) introduces the native API
## Shutdown
Whoever starts the client also stops it:
- With `runBot`, the runner owns the client. In the default API, Ctrl+C or a stop request from a process manager stops the bot unless `processSignals` is `false`. The runner then gives running handlers up to 5 seconds to finish, cancels what is left, closes the connection, waits for cleanup and returns. When the bot stopped because of a failure, the runner logs it and sets the process exit code to 1
- With `createClient`, the application owns the client and must call `shutdown()`, or declare it with `await using` so it shuts down at the end of the block
Shutdown waits for the SDK's own work, not for other promises the application started. The [bot lifetime guide](https://fluxerly.neontechspace.com/docs/starter-lifetime.md) covers what the runner owns and what the application owns
---
# Create a Fluxer bot and get its token
Create the application, copy its token and invite the bot to a community
A Fluxer bot is an application with its own bot account. This page creates the application, keeps its token private and adds the bot to a community, which is what the API calls a [guild](https://fluxerly.neontechspace.com/docs/glossary.md#guild). The [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) then makes the bot answer its first command
## What is needed
- Node.js 26.13 or newer, which Fluxerly is tested against. Run `node --version` to check
- A registered Fluxer account. If the Fluxer app shows **Claim account**, use it first to add an email and password, because an unclaimed account cannot create applications
- A community where that account has the `ManageGuild` or `Administrator` permission, such as a private test community
## 1. Create the application
1. Sign in to Fluxer with the account that should own the bot
2. Open **User settings** with the gear button next to the microphone and speaker buttons
3. Under **Developer**, choose **Applications**
4. Choose **Create application**, enter an **Application name** and choose **Create**
Fluxer creates the bot account together with the application and opens the application's page. The bot's username comes from the application name when that name is available, otherwise Fluxer picks another one
The page shows the **Application ID** with a **Copy ID** button. Note it for the invite link below. It is not secret, and the bot account's user ID is the same number
Fluxer's API reference describes [what creating an application returns](https://docs.fluxer.com/http-api/applications/#create-application)
## 2. Copy the token
On the application's page, the **Secrets & tokens** section shows the **Bot token**. Fluxer shows the token only right after the application is created or after **Regenerate**, so copy it now and keep it somewhere private, such as a password manager, until the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) saves it in the bot's `.env` file. Anyone holding the token can act as the bot, so keep it out of source code, chat messages, screenshots and logs
If the token leaks or gets lost
Choose **Regenerate** next to the bot token. The old token stops working at once, and every running copy of the bot is disconnected. Put the new token in `.env` and start the bot again
A token has the form `.`, so the part before the dot is the application ID. Fluxer's [token formats](https://docs.fluxer.com/authentication/#token-formats) and [credential handling](https://docs.fluxer.com/authentication/#credential-handling) notes cover the details
## 3. Invite the bot to a community
An invite link opens Fluxer's page for adding the bot to a community. The quick start needs three [permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md):
- `ViewChannel`, to see the channel where a command is typed
- `SendMessages`, to reply
- `ReadMessageHistory`, to read earlier messages in the channel
Together these make the permission value 68608. Paste the application ID into the offline builder below to generate the installation link, the matching [`fluxerly invite`](https://fluxerly.neontechspace.com/docs/cli.md#build-an-installation-url-with-invite) command and the `links.installation` snippet without leaving the page:
Replace `APPLICATION_ID` in this link with the application ID, then open it in a browser:
```text
https://fluxer.com/oauth2/authorize?client_id=APPLICATION_ID&scope=bot&permissions=68608
```
With the SDK installed, the CLI builds and validates the same link offline:
```sh
npx --no fluxerly invite 1234567890123456789 --permissions ViewChannel,SendMessages,ReadMessageHistory
```
In code, `links.installation` and `permissionBits.from` check the application ID and permission names locally:
```ts
import { links, permissionBits } from "@neontechspace/fluxerly"
const permissions = permissionBits.from(["ViewChannel", "SendMessages", "ReadMessageHistory"])
const url = links.installation("1234567890123456789", { permissions })
```
Fluxer asks which account to use, then which community to add the bot to, and shows the requested permissions. Choose **Authorise** on the last step. Fluxer creates a role named after the application with exactly these permissions and gives it to the bot
The application's page also has an **OAuth2 URL builder** section that builds such a link from chosen scopes and **Bot permissions**. Once the SDK is installed, [`fluxerly invite`](https://fluxerly.neontechspace.com/docs/cli.md#build-an-installation-url-with-invite) and `links.installation` validate the application ID and permission names locally so a typo fails instead of producing a broken link
If the bot cannot be added
- Adding a bot needs the `ManageGuild` or `Administrator` permission in the chosen community
- Only an administrator can give the bot a permission that the person adding it does not have
- A private bot can be added only by the account that owns the application
- A bot that is already in the community cannot be added again
The role Fluxer creates for the bot stays in the community if the bot leaves. The [consent step](https://docs.fluxer.com/http-api/oauth2/#grant-oauth2-consent) in Fluxer's API reference lists every outcome
## Next
Continue with the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) to generate the project, save the token in it and answer `!ping`
---
# Deploy a bot
Keep a bot running with PM2, systemd or Docker, with the token in the environment and a clean shutdown
A deployed bot is an ordinary Node.js process. A process manager starts it, passes the token through the environment, restarts it after a crash and stops it with a signal: SIGINT under PM2 and SIGTERM under systemd and Docker
A bot started with the default API's `runBot` handles both signals by default, closes the connection cleanly and lets the process exit. The native Effect `runBot` handles them only with `processSignals: true`, because an Effect launcher such as `NodeRuntime.runMain` already interrupts the program on both signals
## Prepare the bot
Every setup below expects the same project:
- Node.js 26.13 or newer on the server or in the image
- The `"type": "module"` field in `package.json`, because the SDK is ESM-only
- A bot started with `runBot`. The default API stops cleanly on SIGINT and SIGTERM unless `processSignals` is `false`. The native Effect API does so only when `processSignals` is `true`, and otherwise relies on its launcher to stop the program on those signals
- The token read from `process.env.FLUXER_BOT_TOKEN`, never written in a source file, committed to version control or copied into an image
- No extra exit handling: When a failure stops the bot, `runBot` sets `process.exitCode` to 1, so the process manager can tell a crash from a normal stop
For local runs, keep the token in a `.env` file that version control ignores, and let Node.js load it
```sh
node --env-file=.env bot.js
```
The file holds one `KEY=value` line per variable. Write the value without quotes so Docker's `--env-file` reads the same file correctly
```text
FLUXER_BOT_TOKEN=paste-the-token-here
```
For TypeScript, run `bot.ts` instead of `bot.js`. Node.js 26 runs TypeScript files directly, so no build step is required
## What happens on shutdown
In the default API, unless `processSignals` is `false`, the SDK listens for SIGINT and SIGTERM and for no other signals. The native Effect `runBot` listens only with `processSignals: true`, so enable it when nothing else handles the signals and a drained stop is wanted. Without it, a launcher such as `NodeRuntime.runMain` interrupts the program instead, which skips the drain below, and with no launcher Node.js ends the process at once
When the process receives one of the signals, the SDK logs the signal and shuts the bot down:
- Stops accepting new events and gives running handlers, commands and scheduled tasks, the events already waiting for them and their requests up to 5 seconds to finish. Scheduled tasks that have not started are cancelled. The `drainMs` option of `runBot` changes that time, and `drainMs: 0` skips the wait
- Signals the handlers and tasks still running to stop through their `signal`
- Closes the command router and every event subscription
- Closes each gateway connection, giving it up to 5 seconds to close normally
- Saves resumable sessions when a [session store](https://fluxerly.neontechspace.com/docs/sharding.md#resume-after-a-restart) is configured. Saves for local shards run in parallel, each with a 5-second timeout
- Waits for the SDK's own cleanup of sockets, requests and collector callbacks
- Finally logs `Shutdown complete` with its duration, removes its signal listeners and resolves the `runBot` Result
The SDK never calls `process.exit`. The process exits once nothing else keeps Node.js running. After `runBot` resolves, close database connections, timers and servers the application opened. A returned handler Promise, a running scheduled task and their REST requests get the drain window to finish. Track detached Promises, timers not started with `client.schedule` and work that needs more than that window, as shown in [application supervision](https://fluxerly.neontechspace.com/docs/application-supervision.md#drain-application-owned-work)
Use a 30-second stop timeout before the process manager force-kills the bot. With the default `drainMs`, allow up to 5 seconds for the drain, up to 5 seconds to close gateway connections and up to 5 seconds for parallel session saves when a store is configured, plus time for remaining SDK cleanup and the application's cleanup after `runBot` resolves
Increase the timeout when `drainMs` is larger or application cleanup needs longer. A force-kill before session saves finish can prevent resuming after restart. Each listener handles only the first signal of its kind, so sending the same signal again during shutdown gets Node.js's default handling and usually ends the process at once
## Logs
The default API writes Info and Debug records to standard output and warnings and errors to standard error. When output is not a terminal, as under every setup below, each record is one JSON object per line, ready for a log collector. Set `FLUXERLY_LOG_FORMAT=pretty` in the environment for readable lines instead
The native Effect API uses the application's Effect logger unless `logging.format` is set explicitly. Set `logging: { format: "json" }` for the same JSON output, or `logging: { format: "pretty" }` for readable lines. The [logging guide](https://fluxerly.neontechspace.com/docs/logging.md) covers levels and categories
## Run with PM2
PM2 reads an ecosystem file. Because the project uses `"type": "module"`, name it `ecosystem.config.cjs`
```cjs
module.exports = {
apps: [
{
name: "fluxer-bot",
cwd: __dirname,
script: "bot.js",
node_args: "--env-file=.env",
exp_backoff_restart_delay: 1000,
kill_timeout: 30000,
},
],
}
```
PM2 restarts the bot whenever it exits, and `exp_backoff_restart_delay` makes it wait longer after each quick failure. PM2 stops an app by sending SIGINT and force-kills it after `kill_timeout`, whose default of 1.6 seconds is shorter than a graceful gateway close
Install PM2 using its [installation guide](https://pm2.keymetrics.io/docs/usage/quick-start/#installation) before running these commands
```sh
pm2 start ecosystem.config.cjs
pm2 logs fluxer-bot
pm2 save
```
The `pm2 save` command records the running apps, and `pm2 startup` prints the command that starts PM2 again after a reboot
## Run with systemd
Before enabling this service, create the `fluxer-bot` system user and install the bot and its dependencies in `/srv/fluxer-bot`. That user must be able to read the project and run Node.js
Create a unit file such as `/etc/systemd/system/fluxer-bot.service`
```ini
[Unit]
Description=Fluxer bot
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=fluxer-bot
WorkingDirectory=/srv/fluxer-bot
EnvironmentFile=/etc/fluxer-bot.env
ExecStart=/usr/bin/node bot.js
Restart=on-failure
RestartSec=5
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target
```
Put `FLUXER_BOT_TOKEN=...` in `/etc/fluxer-bot.env`, owned by root and readable only by root (`chmod 600`). The service manager reads the file before starting the service, so the bot's own user does not need access to it. Adjust the `node` path to the output of `command -v node`
By default, systemd stops a service with SIGTERM and waits `TimeoutStopSec` before force-killing it. The `Restart=on-failure` setting restarts the bot after a non-zero exit code or a crash, but not after a clean stop
```sh
sudo systemctl daemon-reload
sudo systemctl enable --now fluxer-bot
journalctl -u fluxer-bot -f
```
For a [supervisor](https://fluxerly.neontechspace.com/docs/sharding.md#run-shards-in-several-processes) that runs child processes, add `KillMode=mixed` so SIGTERM reaches only the parent, which then stops its children
## Run with Docker
Keep the token and local files out of the image with a `.dockerignore` file next to the `Dockerfile`
```text
.env
node_modules
```
```dockerfile
FROM node:26-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
USER node
CMD ["node", "bot.js"]
```
The `node:26-slim` image tracks the newest Node.js 26 release. Adjust the copy and install lines for pnpm or another lockfile
```sh
docker build -t fluxer-bot .
docker run -d --name fluxer-bot --init --stop-timeout 30 --restart unless-stopped --env-file .env fluxer-bot
docker logs -f fluxer-bot
```
The token reaches the container only at run time through `--env-file`. The `--init` flag runs a small init process that forwards signals to Node.js. The `docker stop` command sends SIGTERM, and `--stop-timeout 30` on `docker run` gives shutdown 30 seconds before a force-kill. With `--restart unless-stopped`, Docker restarts the bot after it exits unless it was stopped on purpose
### Keep session and reminder files
File-backed sessions and reminders need a writable folder that survives container replacement. Reuse the same named volume at `/data` on this Docker host, set `fileSessionStore("/data/sessions")` and keep reminder data at `/data/reminders.json`. Keep local state files out of the image
Add these lines to `.dockerignore`:
```text
sessions
reminders.json
```
Add this line to the `Dockerfile` before `USER node`:
```dockerfile
RUN install -d -o node -g node -m 0700 /data
```
Then add the volume to `docker run`:
```sh
docker run -d --name fluxer-bot --init --stop-timeout 30 --restart unless-stopped --env-file .env --mount type=volume,src=fluxer-bot-data,dst=/data fluxer-bot
```
## Restart policy
Restart after a crash, but with a delay: A bot that fails at startup, for example with a rejected token, fails again at once. Each setup above adds one: PM2 through `exp_backoff_restart_delay`, systemd through `RestartSec` and Docker through its own growing restart delay. Each restart creates a new client and a new gateway session. Events that arrived while the bot was down are not replayed unless a [session store](https://fluxerly.neontechspace.com/docs/sharding.md#resume-after-a-restart) lets a quick restart resume the previous session
Which failures end the process?
The SDK keeps the bot running through handler failures, dropped events and lost connections, and reconnects on its own.
The `runBot` Result fails, and the process exits with code 1, for a startup failure such as a rejected token or an unreachable instance, a connection failure the SDK cannot recover from, or a failed `setup` callback.
Invalid options throw `ConfigurationError` before connecting.
The [reliability guide](https://fluxerly.neontechspace.com/docs/reliability.md) and [troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md) explain these failures
---
# Patterns that work differently
Common bot habits that Fluxerly handles in its own way, each with the call to use instead
Some habits from other bot code do not apply to Fluxerly. Each section names one and shows what to write instead
## Start the bot with runBot
There is no `new Client()` and `client.login(token)`. Pass the token and everything else to `runBot({ token, ... })`:
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({ token: process.env.FLUXER_BOT_TOKEN, events: { messageCreate: () => {} } })
```
When the application controls the connection itself, call `createClient({ token })` and then `client.run()`:
```ts
import { createClient, orThrow } from "@neontechspace/fluxerly"
await using client = createClient({ token: process.env.FLUXER_BOT_TOKEN })
orThrow(await client.run())
```
## Receive events without intents
Fluxer has no intents, so nothing needs to be enabled to receive events, except presence updates for chosen members, which need [`client.presence.setMembers`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#presence-setmembers). Register a handler, and Fluxer's own permissions and visibility decide what arrives. The [configuration guide](https://fluxerly.neontechspace.com/docs/configuration.md#events-and-the-gateway) explains how to skip events the bot does not use
## Use prefix commands
There are no slash commands or interactions. Commands are prefix commands such as `!ping`, set up through the `commands` option of `runBot`:
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: { prefix: "!", commands: { ping: { description: "Check the bot", execute: ({ reply }) => reply("Pong!") } } },
})
```
## Act through the client, not the message
Messages are plain data without methods, so `message.reply()`, `message.delete()` and `channel.send()` do not exist. Use the `reply` passed to a handler, or `client.messages.send(channelId, content)` and the other client methods:
```ts
import type { Client, Message } from "@neontechspace/fluxerly"
export async function answerAndClean(client: Client, message: Message) {
const sent = await client.messages.send(message.channelId, "Noted")
if (sent.isErr()) return sent
return client.messages.delete(message)
}
```
## Read the handler's context object
A `runBot` event handler receives a context object such as `({ message, reply })`, not the message itself:
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
events: { messageCreate: ({ message, reply }) => (message.content === "hi" ? reply("Hello") : undefined) },
})
```
## Check isBot for bot authors
A bot author is detected with `message.author.isBot`. There is no `message.author.bot`, and `runBot` already skips messages from bots unless `ignoreBots` is false
## Communities are guilds
Fluxer calls servers communities, and the SDK names them guilds, as in `guildId` and `client.guilds`
---
# Compose and test an Effect application
Put the scoped client behind application services and replace those services in tests
An Effect application can provide the SDK client as a service, beside its own services. Handlers then use both without starting another runtime, and tests replace the application services without a Fluxer connection
## Define application services and handlers
Keep the handler separate from the services it calls. In the running bot, the reply service uses the SDK client. In tests, replace that service without changing `handlePing`
```ts
// bot.ts
import { Config, Context, Effect, Layer } from "effect";
import { FluxerClient, type Message } from "@neontechspace/fluxerly/effect";
export class GreetingStore extends Context.Service<
GreetingStore,
{ readonly greetingFor: (userId: string) => Effect.Effect }
>()("example/GreetingStore") {}
export class BotReplies extends Context.Service<
BotReplies,
{
readonly reply: (
message: Message,
content: string,
) => Effect.Effect;
}
>()("example/BotReplies") {}
export const handlePing = (message: Message) =>
Effect.gen(function* () {
if (message.author.isBot || message.content !== "!ping") return;
const store = yield* GreetingStore;
const replies = yield* BotReplies;
yield* Effect.sleep("100 millis");
yield* replies.reply(
message,
yield* store.greetingFor(message.author.id),
);
});
export const clientLayer = FluxerClient.layerConfig({
token: Config.Redacted("FLUXER_BOT_TOKEN"),
});
export const repliesLayer = Layer.effect(
BotReplies,
FluxerClient.use((client) =>
Effect.succeed({
reply: (message: Message, content: string) =>
client.messages.reply(message, content).pipe(Effect.asVoid),
}),
),
).pipe(Layer.provideMerge(clientLayer));
```
The `FluxerClient` service holds one native client. `FluxerClient.layerConfig` reads the token from the `FLUXER_BOT_TOKEN` environment variable through Effect `Config`, keeps it redacted and creates the client inside the Layer's scope, without connecting. Closing the application scope shuts the client down once. `BotReplies` lets the handler send replies without depending directly on SDK methods
Layer failures and other ways to build the client service
A missing `FLUXER_BOT_TOKEN` fails the Layer with `ConfigError` before any client exists. A blank token or another invalid setting is misuse, so the Layer dies with `ConfigurationError`. `FluxerClient.layer(options)` takes the same settings as `createClient` without reading `Config`. Each build of a Layer creates its own client, so provide one Layer value to share it. For a `messageFields` selection, call `createClient` directly instead. The next example shows that form
## Assemble the live program
A bot that needs no custom Layer assembly can use `runBot` from the Effect entry point. Its handlers can require application services, and it watches its subscriptions and connection itself. See [first Effect bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md)
For full control, a worker service registers the handlers and runs the client. The worker Layer needs a client, which must stay available until the worker stops. `Layer.provideMerge` keeps both services available, and Layer memoization makes them share one client. This version creates its client service with `createClient` from a token argument
```ts
import { Context, Effect, Layer } from "effect";
import { createClient, type Client } from "@neontechspace/fluxerly/effect";
class AppConfig extends Context.Service<
AppConfig,
{ readonly token: string }
>()("example-live/AppConfig") {}
class BotClient extends Context.Service()(
"example-live/BotClient",
) {}
class GreetingStore extends Context.Service<
GreetingStore,
{ readonly greetingFor: (userId: string) => Effect.Effect }
>()("example-live/GreetingStore") {}
class BotWorker extends Context.Service<
BotWorker,
{ readonly run: Effect.Effect }
>()("example-live/BotWorker") {}
export const liveApplication = (token: string) => {
const config = Layer.succeed(AppConfig, { token });
const clients = Layer.effect(
BotClient,
AppConfig.use((appConfig) => createClient({ token: appConfig.token })),
).pipe(Layer.provide(config));
const workers = Layer.effect(
BotWorker,
BotClient.use((client) =>
Effect.succeed({
run: Effect.scoped(
Effect.gen(function* () {
const subscription = yield* client.on(
"messageCreate",
(message) => {
if (
message.author.isBot ||
message.content !== "!ping"
)
return Effect.void;
return GreetingStore.use((greetings) =>
greetings
.greetingFor(message.author.id)
.pipe(
Effect.flatMap((content) =>
client.messages
.reply(message, content)
.pipe(Effect.asVoid),
),
),
);
},
);
const criticalWorker = subscription.waitForClose().pipe(
Effect.flatMap(() =>
Effect.fail({
_tag: "CriticalWorkerStopped" as const,
}),
),
);
yield* Effect.raceFirst(client.run(), criticalWorker);
}),
),
}),
),
).pipe(Layer.provideMerge(clients));
const store = Layer.succeed(GreetingStore, {
greetingFor: (userId) => Effect.succeed(`Pong for ${userId}`),
});
const program = BotWorker.use((worker) => worker.run);
return Effect.scoped(
program.pipe(Effect.provide(Layer.mergeAll(config, workers, store))),
);
};
```
This example includes its own handler and client service so it can be copied alone. An application can import `handlePing` from the previous section instead, and use `FluxerClient` with `clientLayer` in place of `BotClient`
Run `subscription.waitForClose()` and `client.run()` together for every subscription the bot needs, stopping when either finishes. `Effect.raceFirst` stops the other operation and the surrounding scope runs cleanup
When a subscription stops
If a subscription closes unexpectedly without an error, report `CriticalWorkerStopped`. A typed subscription error remains the application failure. A failed subscription must either stop the bot or trigger a restart with a limit on attempts. Effect does not replay failed event handlers
## Replace application services in a deterministic test
This test supplies fake database and reply services to the unchanged handler. `TestClock` advances only the application-owned `Effect.sleep` in `handlePing`
```ts
// bot.test.ts
import assert from "node:assert/strict";
import { test } from "node:test";
import { Effect, Fiber, Layer } from "effect";
import { TestClock } from "effect/testing";
import type { Message } from "@neontechspace/fluxerly/effect";
import { BotReplies, GreetingStore, handlePing } from "./bot.ts";
export function testPing(message: Message, replies: Array) {
const fakes = Layer.mergeAll(
Layer.succeed(GreetingStore, {
greetingFor: (userId) => Effect.succeed(`Hello ${userId}`),
}),
Layer.succeed(BotReplies, {
reply: (_message, content) =>
Effect.sync(() => replies.push(content)),
}),
);
return Effect.gen(function* () {
const fiber = yield* handlePing(message).pipe(
Effect.provide(fakes),
Effect.forkChild,
);
yield* TestClock.adjust("100 millis");
yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer()));
}
test("!ping replies with the stored greeting", async () => {
const replies: Array = [];
const message = {
content: "!ping",
author: { id: "42", isBot: false },
} as unknown as Message;
await Effect.runPromise(testPing(message, replies));
assert.deepEqual(replies, ["Hello 42"]);
});
```
Save it as `bot.test.ts` beside `bot.ts` and run `node --test --test-timeout=10000 --test-force-exit`. The test runs the Effect and checks the result, so a missing reply fails
The test does not open a gateway or replace SDK internals. It replaces the application services used by the handler
## Test a runBot bot against an in-memory Fluxer
To check the requests a bot really sends, pass its native `runBot` options to `createTestBot` from `@neontechspace/fluxerly/effect/testing`. It creates a real native client connected to an in-memory Fluxer, owned by the test's Scope, and registers the bot's events, commands and setup as `runBot` would. The unset token falls back to a test token. For a bot file that exports its options with `defineBot`, such as the one `fluxerly init --template effect` writes, pass the imported `bot`
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { Effect } from "effect"
import { createTestBot } from "@neontechspace/fluxerly/effect/testing"
export const pingTest = Effect.scoped(
Effect.gen(function* () {
const bot = yield* createTestBot({
token: process.env.FLUXER_BOT_TOKEN,
events: {
messageCreate: ({ message, reply }) =>
message.content !== "!ping" ? Effect.void : reply("Pong!"),
},
})
yield* bot.ready()
const replies = yield* bot.say("!ping")
const ignored = yield* bot.say("hello")
return { replies: replies.map((message) => message.content), ignored: ignored.length }
}),
)
test("!ping replies Pong! and other messages get no reply", async () => {
assert.deepEqual(await Effect.runPromise(pingTest), { replies: ["Pong!"], ignored: 0 })
})
```
The `say` Effect delivers a message from a fake user as Fluxer would send it, waits until the bot has stopped working and returns the messages the bot sent meanwhile. The fake Fluxer API answers each message the bot sends with that message, so no response needs registering. The list shows what the bot tried to send, even when `rest.respond` rejected the request, and a failure that an `onError` hook handled does not appear in `failures()`
For other events, `emit` delivers a gateway event, `idle()` waits until the bot has stopped working, and `rest.respond` controls how the fake Fluxer API answers a request. These waits have no deadline unless `timeoutMs` is passed, so run tests with `node --test --test-timeout=10000 --test-force-exit` to fail a bot that never settles
The test gateway enforces the Identify session's `gateway.ignoredEvents`: The `emit` Effect dies with `ConfigurationError` when Fluxer would suppress that dispatch, without consuming a sequence number. With automatic filtering, register handlers before running `ready()` so Identify sees them. Resume keeps the list, while a new Identify recomputes it. Suppressed message mentions and generated reaction batches follow Fluxer's exceptions, described in [Match gateway event filtering](https://fluxerly.neontechspace.com/docs/testing.md#match-gateway-event-filtering)
The `failures()` method returns handler and command failures that no `onError` hook received, including a failed SDK call such as a rejected reply, whatever the logging level
Closing the Scope dies with `UnhandledTestFailuresError` when such a failure happened and the test did not read it from `failures()`, so a broken handler fails the test. For code that registers handlers with `client.on`, `createTestClient` creates the same test client without bot options. See [Test a bot without Fluxer](https://fluxerly.neontechspace.com/docs/testing.md) and the [Effect testing reference](https://fluxerly.neontechspace.com/docs/api/effect-testing/)
Control SDK time with TestClock
A native client captures the provided Effect `Clock` when `createClient` runs. Create the client inside the same provided Clock and Scope context when a test needs logical SDK time. `TestClock` can then advance event waits, message and reaction collectors, member-chunk timeouts, native command cooldowns, queued REST admission and deadlines, cache expiry, and presence or member-subscription pacing without real waiting
`TestClock` does not control protocol timestamps such as an HTTP-date `Retry-After`, external I/O including WebSockets, or process shutdown watchdogs. Those cases still need controlled transport responses or tests using real time
Fake timers from a test runner, such as Vitest's `vi.useFakeTimers()`, work differently from `TestClock`. A `timeoutMs` on `next()`, `idle()` or `say` uses real timers, so faking the global timers does not change it. The SDK runs its work on `setImmediate`, so fake timers must leave `setImmediate` real, as in `vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date"] })`. When `setImmediate` is faked, no handler can run, and `idle()` dies with `ConfigurationError` instead of settling
## Test a conversation that waits for a reply
A command that asks a question and waits for the answer, such as the collector in [Collect replies and clean up](https://fluxerly.neontechspace.com/docs/effect-workflows.md#collect-replies-and-clean-up), keeps `say` waiting, because `say` waits for the command to finish and the command waits for the answer. Register a route for the question, deliver the first message with `emit`, and wait for the question with the route's `next()`. Then `say` can send the answer
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { Effect } from "effect"
import { createTestBot } from "@neontechspace/fluxerly/effect/testing"
export const conversationTest = Effect.scoped(
Effect.gen(function* () {
const bot = yield* createTestBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
name: {
execute: ({ client, message, reply }) =>
Effect.scoped(
Effect.gen(function* () {
const collector = yield* client.messages.collect(message.channelId, {
filter: (answer) => answer.author.id === message.author.id,
maxMessages: 1,
timeoutMs: 30_000,
})
yield* reply("What name should the bot use?")
const answer = (yield* collector.result()).messages[0]
return yield* reply(answer ? `Hello, ${answer.content}!` : "No answer in time")
}),
),
},
},
},
})
const questions = bot.rest.respond("POST /channels/:id/messages", (request) => ({
body: bot.fixtures.message({
author: bot.fixtures.botUser(),
content: String((request.body as { content?: unknown }).content),
}),
}))
yield* bot.ready()
yield* bot.emit("MESSAGE_CREATE", bot.fixtures.message({ content: "!name" }))
const question = yield* questions.next()
const replies = yield* bot.say("Ada")
return {
question: (question.body as { content?: unknown }).content,
replies: replies.map((message) => message.content),
}
}),
)
test("!name asks for a name and greets the answer", async () => {
assert.deepEqual(await Effect.runPromise(conversationTest), {
question: "What name should the bot use?",
replies: ["Hello, Ada!"],
})
})
```
To test the timeout instead, create the bot under `TestClock`, as described in Control SDK time with TestClock above, advance it past `timeoutMs` after the question arrives, and call `idle()`. The default API's `say` returns early while a command waits on its manual clock, but a native client under `TestClock` has no such shortcut
## Provide the test client as the FluxerClient service
Code that reads its client from the `FluxerClient` service, like `repliesLayer` in the first section, runs against the in-memory Fluxer unchanged. `FluxerTestClient.layer()` from `@neontechspace/fluxerly/effect/testing` creates a test client and provides its client as `FluxerClient`. The same Layer provides the whole test client as `FluxerTestClient`, whose controls drive the test
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { Effect } from "effect"
import { FluxerClient } from "@neontechspace/fluxerly/effect"
import { FluxerTestClient } from "@neontechspace/fluxerly/effect/testing"
const registerPing = Effect.gen(function* () {
const client = yield* FluxerClient
yield* client.on("messageCreate", (message) =>
message.content === "!ping" ? client.messages.reply(message, "Pong!") : Effect.void,
)
})
export const serviceTest = Effect.gen(function* () {
yield* registerPing
const testClient = yield* FluxerTestClient
const replies = testClient.rest.respond("POST /channels/:id/messages", {
body: testClient.fixtures.message({ content: "Pong!" }),
})
yield* testClient.ready()
yield* testClient.emit("MESSAGE_CREATE", testClient.fixtures.message({ content: "!ping" }))
return yield* replies.next()
}).pipe(Effect.scoped, Effect.provide(FluxerTestClient.layer()))
test("registerPing sends the reply", async () => {
const request = await Effect.runPromise(serviceTest)
assert.equal((request.body as { content?: unknown }).content, "Pong!")
})
```
The `FluxerTestClient.layer(options)` method accepts the options of `createTestClient` except `messageFields`, because `FluxerClient` holds full messages. Closing the Layer's scope shuts the client down, as the live Layer does, and dies with `UnhandledTestFailuresError` for a handler failure the test did not read from `failures()`
---
# Learn Effect with a bot
Understand the small set of Effect concepts needed to send a message and run a bot
Effect is optional. The [default JavaScript and TypeScript API](https://fluxerly.neontechspace.com/docs/quick-start.md) supports the same SDK capabilities with `async` functions and Results
Use the native Effect API when several bot operations must stop together, resources must close and failures need separate handling. Those operations can use the same services and cleanup scope as the rest of an Effect application
The examples introduce each Effect concept before combining them into a bot
## Install the matching version
To start from a generated Effect project with a test, run the command from [Generate the project](https://fluxerly.neontechspace.com/docs/quick-start.md#generate-the-project) with `--template effect` in the bot's folder, which may already hold the token's `.env` and a `.gitignore`
First generate a project with [the quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) and choose Effect, which installs the SDK, Effect, TypeScript 7 and the Node.js types for typechecking. Fluxerly is tested against Node.js 26.13 or newer. A project set up by hand needs `"type": "module"` in `package.json` and the TypeScript setup that the quick start's TypeScript section describes. Native examples use TypeScript
Fluxerly works with Effect 4. The installed SDK lists its accepted range under `peerDependencies.effect` in `node_modules/@neontechspace/fluxerly/package.json`. Effect 3 and Effect 4 prereleases are incompatible
These examples import Effect directly, so declare it as a direct dependency. For this documentation version, the command is:
```sh
npm install effect
```
Check which Effect version the application has installed:
```sh
npm list effect
```
Recheck the required version when upgrading the SDK. The [Effect v4 learning material](https://effect.website/docs/v4/getting-started/why-effect) matches this major version
## Start with one request
An Effect describes work but does not run it yet. `Effect.runPromise` runs it from the application's top-level code
```ts
import { Effect } from "effect"
import { createClient } from "@neontechspace/fluxerly/effect"
export function sendHello(token: string, channelId: string) {
const program = Effect.scoped(
Effect.gen(function* () {
const client = yield* createClient({ token })
return yield* client.messages.send(channelId, "Hello from Effect")
}),
)
return Effect.runPromise(program)
}
```
Call `sendHello` with a private bot token and a channel the bot can write to. It resolves to the sent message after the client has finished cleanup. Sending through REST does not need a gateway connection
Read the program in order:
1. `Effect.gen` writes sequential work using a generator function
2. The `yield*` expression runs an Effect and returns its successful value. An expected failure skips the remaining steps unless handled
3. `Effect.scoped` supplies a cleanup lifetime. When that lifetime ends, Fluxerly closes the client and waits for its owned cleanup
4. `Effect.runPromise` runs the program and returns a JavaScript Promise
Each `yield*` provides the successful value directly, while failures remain part of the Effect's type. Running the same description twice repeats its requests, including writes
## Add a message handler
Native handlers must return an Effect. For an existing native client, `client.on` provides a subscription
```ts
import { Effect } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function installPing(client: Client) {
return client.on("messageCreate", message => {
if (message.author.isBot || message.content !== "!ping") return Effect.void
return client.messages.reply(message, "Pong!")
})
}
```
`Effect.void` describes doing nothing successfully. Returning the reply Effect lets the SDK run and cancel it with the handler. Calling `Effect.runPromise` inside each callback would run that work separately from the handler
## Run the complete bot
This is the bot that `fluxerly init --template effect` writes. Save it as `bot.ts` and start it with `node --env-file=.env bot.ts`, using the `.env` file from the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md). The `defineBot` function holds the bot's options and returns them unchanged, keeping the types of command arguments and the services that handlers require. The runner registers the commands before it connects
```ts
import { Effect } from "effect"
import { defineBot, runBot } from "@neontechspace/fluxerly/effect"
// The bot's options without its token, so its test can run them through createTestBot without a token or a network
export const bot = defineBot({
commands: {
prefix: "!",
commands: {
// A failed reply is reported to the log without stopping the bot
ping: { execute: ({ reply }) => reply("Pong!") },
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main)
await Effect.runPromiseExit(runBot({ token: process.env.FLUXER_BOT_TOKEN, processSignals: true, ...bot }))
```
Send `!ping` and expect `Pong!`. Press Ctrl+C to stop the bot. The SDK interrupts it and waits for its cleanup
The last line passes the options and the token to `runBot` and runs that program with `Effect.runPromiseExit`, which resolves with the program's outcome, called an Exit, instead of rejecting. The line runs only when Node.js runs the file, so a test can import `bot` without starting it, as the [Effect application testing guide](https://fluxerly.neontechspace.com/docs/effect-application-testing.md#test-a-runbot-bot-against-an-in-memory-fluxer) shows
The `runBot` program reports its own failure: A failure that stops the bot, such as a rejected token, is logged once and sets `process.exitCode` to 1, so the Exit needs no further handling. Setting the exit code instead of calling `process.exit()` lets Node.js finish cleanup before the process ends
What the runner watches while the bot runs
The runner registers the handler before the gateway connects and then watches both the connection and the handler's subscription. A connection failure, or a subscription that closes unexpectedly, stops the bot and waits for cleanup.
A failed handler is reported and not retried, and the bot keeps running. Returning the `reply` Effect lets the SDK interrupt it when the handler stops.
Keep the token private, including in the environment and in process-manager settings
The [small bot](https://fluxerly.neontechspace.com/docs/small-bot.md) guide shows a larger native bot with commands, a permission guard, a cooldown and a welcome message
## Report failures outside runBot
Application code outside `runBot`, such as a one-off job, reports its own failure. A failed Exit holds a Cause, Effect's full record of why the program failed. Pass `exit.cause` to `describeError`, which prints each error's code, hint and details with recognized credentials masked
```ts
import { Effect, Exit } from "effect"
import { createClient, describeError } from "@neontechspace/fluxerly/effect"
export async function announce(token: string, channelId: string) {
const exit = await Effect.runPromiseExit(
Effect.scoped(
Effect.gen(function* () {
const client = yield* createClient({ token })
yield* client.messages.send(channelId, "Maintenance starts in ten minutes")
}),
),
)
if (Exit.isFailure(exit)) {
console.error(describeError(exit.cause))
process.exitCode = 1
}
}
```
## Read the Effect types
`Effect.Effect` describes the successful value `A`, expected failures `E`, and required services `R`. A client operation can use the same application services as other Effects without the SDK starting a separate runtime
Effect represents expected errors, defects and interruption. A defect is an unexpected fault, and interruption means cancellation. Effect's Cause can retain these together, including cleanup failures. Do not turn every Cause into a retry
Continue with [scoped workflows](https://fluxerly.neontechspace.com/docs/effect-workflows.md) to combine collectors, failure handling and concurrent reads
---
# Build workflows with Effect
Handle expected failures, collect replies and limit concurrent reads
After the [first Effect bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md), these examples take a native `Client` as a parameter. It can come from `createClient`, from the `FluxerClient` service described in [Effect application testing](https://fluxerly.neontechspace.com/docs/effect-application-testing.md) or from the `client` that `runBot` passes to its handlers and `setup`. Each helper returns an [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect). Call it with `yield*` inside the application program
## Handle success and expected failure
Use `Effect.match` to turn either success or an expected failure into a value. For example, a status panel can report whether a notice was sent without storing its content or a raw error
```ts
import { Effect } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function sendNotice(client: Client, channelId: string) {
return client.messages.send(channelId, "The event starts in ten minutes").pipe(
Effect.match({
onSuccess: message => ({ status: "confirmed" as const, messageId: message.id }),
onFailure: error => ({ status: "failed" as const, error }),
}),
)
}
```
The failure branch retains the expected SDK error for the caller. Defects and interruption still propagate to the caller
Decide whether a failed send can be repeated
A message error's `outcome` field is `notDispatched` when the request never left the client, `rejected` when Fluxer refused it, and `unknown` when it may have been delivered. Reconcile an `unknown` outcome before another send attempt, because repeating it can post a duplicate. The `errors.isRetryable(error)` helper, exported by both entry points, says whether repeating the same call is safe. See [reliability](https://fluxerly.neontechspace.com/docs/reliability.md)
## Collect replies and clean up
A nested scope cleans up a short conversation's collector while the bot stays open
```ts
import { Effect } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function askPreferredName(client: Client, channelId: string, userId: string) {
return Effect.scoped(
Effect.gen(function* () {
const collector = yield* client.messages.collect(channelId, {
filter: message => message.author.id === userId && !message.author.isBot,
maxMessages: 1,
timeoutMs: 30_000,
})
yield* client.messages.send(channelId, "What name should the bot use?")
const result = yield* collector.result()
return result.messages[0]?.content
}),
)
}
```
The client must already be connected. The `yield*` expression finishes registration before sending the prompt, so a fast reply can be observed. Success, prompt failure and interruption all release the collector before this helper completes. The outer client stays open
A timeout can return `undefined`. A [gateway gap](https://fluxerly.neontechspace.com/docs/glossary.md#gateway-gap) fails collection because replies may have been missed. The prompt remains posted after collection ends
## Run independent reads together
Fetch independent data at the same time, with a limit on concurrent requests. This example fetches a community and its channels without opening the gateway
```ts
import { Effect } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function readGuildOverview(client: Client, guildId: string) {
return Effect.all({
guild: client.guilds.fetch(guildId),
channels: client.channels.fetchAll(guildId),
}, { concurrency: 2 })
}
```
On success, the result has `guild` and `channels` properties. A failure interrupts unfinished sibling work and waits for its finalizers. The SDK's request limits and rate-limit handling still apply. Concurrent reads can observe different remote revisions
## Count messages without storing them all
A Stream describes values processed as they arrive. A remote scan can run without collecting every result in an array
```ts
import { Stream } from "effect"
import type { Client } from "@neontechspace/fluxerly/effect"
export function countRecentHumanMessages(client: Client, channelId: string) {
return client.messages.iterateHistory(channelId, { maxItems: 200, pageSize: 50 }).pipe(
Stream.runFold(() => 0, (count, message) => count + (message.author.isBot ? 0 : 1)),
)
}
```
The returned Effect counts human-authored observations among at most 200 messages, newest first. Requests begin when the Stream is consumed, page failures remain failures, and interruption waits for in-flight cleanup
## Read history and post a summary
Keep reusable work as Effects and run the completed program at the application entry point. This example creates one scoped client, reads at most 200 messages, sends a summary and then closes the client
```ts
import { Effect, Stream } from "effect"
import { createClient } from "@neontechspace/fluxerly/effect"
export function postActivitySummary(token: string, channelId: string) {
return Effect.scoped(
Effect.gen(function* () {
const client = yield* createClient({ token })
const count = yield* client.messages.iterateHistory(channelId, {
maxItems: 200,
pageSize: 50,
}).pipe(Stream.runFold(() => 0, total => total + 1))
return yield* client.messages.send(channelId, `Scanned ${count} recent messages`)
}),
)
}
```
Run the returned Effect with `Effect.runPromise` from the application entry point, or `yield*` it inside a larger program. A failed history scan skips the summary. Reconcile an [uncertain](https://fluxerly.neontechspace.com/docs/glossary.md#uncertain-write) summary delivery before rerunning the job, which can otherwise post a duplicate
For the next step, learn [Effect resource management](https://effect.website/docs/v4/resource-management/introduction) and [expected errors versus defects](https://effect.website/docs/v4/error-management/two-error-types). Use services and Layers to supply shared application dependencies
---
# Use emoji, reactions and stickers
Put custom emoji in messages, add reactions, send community stickers and create emoji
Unicode emoji such as 🎉 work directly in message content and reactions. Custom emoji belong to a [community](https://fluxerly.neontechspace.com/docs/glossary.md#guild) and have a name and an ID. Fluxer displays them from markup such as `<:name:id>` for a static image or `` for an animated one
| Task | Input |
| --- | --- |
| Display an emoji in a message | Unicode or custom markup in `content` |
| React to a message | Unicode, custom markup, parsed emoji fields or a `GuildEmoji` |
| Send a sticker | Its ID in `stickerIds` |
| Manage community emoji or stickers | The `client.emojis` or `client.stickers` namespace |
The SDK does not turn shortcodes such as `:party:` into emoji IDs. Look up the name in application code, or configure the ID when several communities have an emoji with the same name
## Find an emoji and use it twice
Fetch a community's emoji and find the configured ID. The helper uses that emoji in a message and as a reaction to it. Add it to a bot that already has a [client](https://fluxerly.neontechspace.com/docs/quick-start.md)
```ts
import { format, type Client } from "@neontechspace/fluxerly"
export async function celebrateWithEmoji(
client: Client,
guildId: string,
channelId: string,
emojiId: string,
) {
const listed = await client.emojis.fetchAll(guildId)
if (listed.isErr()) return listed
const emoji = listed.value.find((item) => item.id === emojiId)
if (!emoji) return
const sent = await client.messages.send(channelId, `Build passed ${format.customEmoji(emoji)}`)
if (sent.isErr()) return sent
return await client.messages.addReaction(sent.value, emoji)
}
```
The helper returns `undefined` when the configured emoji is not in the community. If adding the reaction fails, the sent message stays posted. Fluxer checks that the emoji is available and that the bot has permission for each request
Custom markup can also be passed directly, for example `client.messages.addReaction(message, "")`, with the example ID replaced by an available emoji. The SDK converts it to the form Fluxer's reaction endpoint expects
### Emoji and stickers from age-restricted communities
Fluxer treats a community as age-restricted when it is marked NSFW or set to the age-restricted level. Its custom emoji and stickers work only inside that community, whatever the bot's permissions:
- A new reaction with such an emoji elsewhere fails with reason `rejected` and an `apiError` with code `missingPermissions`. Adding to a reaction that is already on the message still works
- A sticker from such a community fails the same way when it is sent anywhere else
- Such an emoji in message text sent or edited anywhere else becomes plain `:name:` text, so the message is sent without the image
## Reuse a received or parsed emoji
Reaction [events](https://fluxerly.neontechspace.com/docs/glossary.md#event) already contain everything needed to add the same reaction. This [handler](https://fluxerly.neontechspace.com/docs/glossary.md#handler), registered with `client.on`, mirrors each person's reaction with the bot's own. Supply the connected bot's ID so the bot ignores its own reactions
```ts
import { describeError, type Client } from "@neontechspace/fluxerly"
export function mirrorReactions(client: Client, botId: string) {
return client.on("messageReactionAdd", async (reaction) => {
if (reaction.userId === botId) return
const added = await client.messages.addReaction(reaction, reaction.emoji)
if (added.isErr()) console.warn(describeError(added.error))
})
}
```
The `client.on` method returns a subscription. Keep it and call its `close()` method when mirroring should end. The same emoji inputs work for removing reactions, listing the people who reacted and choosing a [collector](https://fluxerly.neontechspace.com/docs/glossary.md#collector)'s emoji. To read custom emoji markup typed by a user, use `format.tryParseCustomEmoji()`, which returns a [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) instead of throwing on invalid text, and pass the parsed value on
Grouped reactions and emoji matching
This example handles one added reaction at a time, which is how reactions in a community always arrive. Fluxer groups additions into a `messageReactionAddMany` event only in direct messages, and only when `gateway.flags.debounceMessageReactions` is set. For a time or item limit that handles both forms, use a [reaction collector](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#accept-a-confirmation-reaction).
Collectors match custom emoji by ID, even after a rename. Unicode emoji match the exact text, including skin tone and variation selectors
## Send a community sticker
Fetch the community's stickers and select one by configured ID. A message can contain up to three sticker IDs, with optional text, embeds and attachments
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function sendGuildSticker(
client: Client,
guildId: string,
channelId: string,
stickerId: string,
) {
const listed = await client.stickers.fetchAll(guildId)
if (listed.isErr()) return listed
const sticker = listed.value.find((item) => item.id === stickerId)
if (!sticker) return
return await client.messages.send(channelId, {
content: "Ready for the next round",
stickerIds: [sticker.id],
})
}
```
Received messages list their stickers in `message.stickers`. Image URLs come from the [asset helpers](https://fluxerly.neontechspace.com/docs/api/js-ts/builders-and-formatting/#assets), and image bytes are downloaded only on request
## Create a reusable community emoji
Supply image bytes from a trusted source. Fluxer decides how large an emoji or sticker image may be, 512 KiB by default, and a community can have a different limit. Creating emoji or stickers needs `CreateExpressions`. Fluxer also checks the image format, dimensions and the community's remaining slots
```ts
import type { Client } from "@neontechspace/fluxerly"
export function createBuildEmoji(client: Client, guildId: string, image: Uint8Array) {
return client.emojis.create(guildId, {
name: "build_passed",
image: Buffer.from(image).toString("base64"),
})
}
```
The returned `GuildEmoji` can be formatted into a message or used as a reaction. Stickers are created with `client.stickers.create` and a name, image and optional description and tags. Both namespaces can also fetch, rename, copy and delete. To find which community owns a custom emoji or sticker, use `emojis.fetchSource(id)` or `stickers.fetchSource(id)`, which Fluxer answers when that community is discoverable or the bot is a member of it
Renaming or deleting an emoji or sticker the bot created needs `CreateExpressions`. Changing another account's emoji or sticker needs `ManageExpressions`. Emoji and stickers from `fetchAll` carry the uploader's user ID as `creatorId`, so a bot with only `CreateExpressions` can tell which ones it may change. Creations, edits and the gateway's community snapshots leave it out, so an emoji or sticker from the cache can lack it
Creating several emoji at once
Batch creation with `createMany` returns separate `success` and `failed` lists, so inspect both. Each failure has the `name` it was given and, when Fluxer explains it, a `providerMessage`, such as a full community or an image Fluxer could not read. That text is localized for a person to read, not a code to match. If the whole request fails with an unknown outcome, some emoji may still have been created, so fetch the community's emoji before retrying. The [reliability guide](https://fluxerly.neontechspace.com/docs/reliability.md) explains these uncertain writes
## Send and react with Effect
The [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect) API accepts the same reaction inputs. This function sends a reply, parses a custom emoji, then reacts to the reply. Run it inside the [Effect bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md)'s existing runtime
```ts
import { Effect } from "effect"
import { format, type Client, type Message } from "@neontechspace/fluxerly/effect"
export function celebrateWithEffect(client: Client, message: Message, emojiMarkup: string) {
return Effect.gen(function* () {
const emoji = yield* format.tryParseCustomEmoji(emojiMarkup)
const sent = yield* client.messages.reply(message, "Build passed")
yield* client.messages.addReaction(sent, emoji)
return sent
})
}
```
Each step adds its possible failures to the function's Effect type. Interrupting the surrounding task stops the remaining steps. A completed reply stays posted if a later step fails
## Wire it up
In a `runBot` bot, a command can reply and then react to its own reply with the `client` from its context. This bot answers `!celebrate` and adds 🎉 to the answer
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
celebrate: {
description: "Celebrate with a reaction",
execute: async ({ client, reply, signal }) => {
const sent = await reply("Build passed")
if (sent.isErr()) return sent
return client.messages.addReaction(sent.value, "🎉", { signal })
},
},
},
},
})
```
Returning the reaction's Result lets the router report a failed reaction with the command name. To mirror reactions instead, add a `messageReactionAdd` handler to the `events` option. Its `event` is the same reaction that `mirrorReactions` above receives, and its context also provides the `client`
---
# React to events and collect replies
Handle gateway events, detect community joins, follow threads, wait for one event and collect replies or reactions for a limited time
Fluxer sends live [events](https://fluxerly.neontechspace.com/docs/glossary.md#event), such as new messages, community joins and reactions, over the [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) connection. A [handler](https://fluxerly.neontechspace.com/docs/glossary.md#handler) registered for an event name runs each time that event arrives. In a `runBot` bot, handlers go in the `events` option, as the [last section](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#wire-it-up) shows
The helpers below take the `client` from the [first bot example](https://fluxerly.neontechspace.com/docs/quick-start.md). Register handlers before connecting so they also receive startup events. Unlike sending or fetching messages, waiting for future events needs a connected gateway
## Distinguish a join from community availability
The `guildCreate` event arrives when the bot joins a community, and also when a community's data becomes available at startup or after an outage. Check `isNewJoin` when a handler should react only to a new join. To know when a member joins a community the bot is already in, handle `guildMemberAdd` instead, which carries the member who joined
```ts
import type { Client } from "@neontechspace/fluxerly"
export function observeGuildJoins(client: Client, rememberGuild: (id: string) => void) {
return client.on("guildCreate", (guild) => {
if (!guild.isNewJoin) return
rememberGuild(guild.id)
})
}
```
The `client.on` method returns a subscription. Call its `close()` method when the handler is no longer needed
The event carries the community itself, not its channels, roles or emoji. To find a channel by name when the bot joins, call `client.channels.fetchAll(guild.id)` in the handler. With `cache: { channels: true }`, the community's channels are also kept from the event, so `client.channels.get(id)` reads one without a request
The event can also carry `memberCount`, `onlineCount` and `joinedAt`, as Fluxer reported them when it delivered the event. They are a snapshot that neither `guildUpdate` nor the guild cache refreshes, so call `guilds.fetchCounts` for current totals. Here `onlineCount` is the guild-wide figure every recipient receives, while `guilds.fetchCounts` counts only the online members the bot can see, so the two can differ
How reliable is isNewJoin?
The `isNewJoin` flag requires a Fluxer gateway that distinguishes new joins from startup community data. It does not guess from timing, readiness or an empty cache, and communities the bot already belonged to when it connected are not reported as new joins.
A replayed event can run the handler again, so check whether a welcome or onboarding action already ran before repeating it
A successful `connect()` means Fluxer accepted the session, not that every community or resource has finished arriving
What else does a handler receive?
A `client.on` handler receives the event, an `AbortSignal` that is aborted when the subscription closes or the client shuts down, and an event context. The context's `shardId` names the shard that received the event, `sessionEpoch` is that shard's session when the event arrived, `receipt` numbers events in the order the client received them, and `receivedBytes` is the size of the gateway message that carried it
Compare receipts to tell which of two events came first, as [`EventContext.receipt`](https://fluxerly.neontechspace.com/docs/api/js-ts/events-and-collectors/#eventcontext-receipt) describes. Work that is not an event, such as a timer, can read `client.lastReceipt` when it starts and treat any event with a larger receipt as newer. For a change or removal, the context's `previous` holds the cached value from before it, as the [next section](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#log-edits-and-deletions) shows
Pass the signal to SDK operations inside the handler so they stop with it. To run code around every handler, such as timing or tracing, register event [middleware](https://fluxerly.neontechspace.com/docs/glossary.md#middleware) with `client.use`
A handler runs one event at a time by default, except a `messageCreate` handler, which runs up to eight at a time so that one slow message does not stall the next ones. Those messages can finish out of order, and `{ concurrency: 1 }` or a `partition` keeps related messages in order
Later events wait in a queue of up to 256 events. When the queue is full, the oldest waiting event is dropped and a Warn record is logged, while the handler keeps running. Pass `{ overflow: "stop" }` as the third argument of `client.on` to close the subscription instead
To handle several events at a time and still keep related events in order, pass a `partition` option. The value `"channel"` keys each event by its channel, `"guild"` by its community, and a function returns a key of its own
Events with different keys run side by side, up to eight at a time unless `concurrency` says otherwise, while events with the same key run one after another in the order they arrived. When the queue is full, a partitioned handler drops from the longest backlog instead of the oldest event overall. The [`overflow`](https://fluxerly.neontechspace.com/docs/api/js-ts/events-and-collectors/#handleroptions-overflow) reference lists how the backlog to drop from is chosen
## Log edits and deletions
Update events carry the new state. A single-message deletion can also carry the deleted text in `content` and the author's ID in `authorId`, even without a cache. When the matching cache is enabled, the handler's context also holds `previous`, the value that cache held just before the change, so a log can show what changed. Enable the message cache for message edits and deletions, the member and role caches for member and role changes, the channel cache for channels and threads, and the guild cache for community changes
Fluxer sends only IDs for a bulk deletion, such as the messages a ban removes, so its `previous` is the only source of their content and authors. It lists the messages the cache held and leaves out the rest, so compare it with the event's `ids` to see how many are unknown
Writes through the SDK's resource methods, such as `messages.edit`, update these caches too. After an edit by the bot, the event that follows can hold the value the edit stored, or no `previous` at all where the write removed the entry, such as a member after a role change. A log that must show the value from before the bot's own edits has to keep that value itself
```ts
import type { Client } from "@neontechspace/fluxerly"
// Create the client with createClient({ token, cache: { messages: true } })
export function logMessageChanges(client: Client, log: (line: string) => void) {
const edits = client.on("messageUpdate", (message, _signal, { previous }) => {
if (previous !== undefined && previous.content !== message.content)
log(`Message ${message.id} was edited from "${previous.content}" to "${message.content}"`)
})
const deletions = client.on("messageDelete", (deletion, _signal, { previous }) => {
const content = deletion.content === undefined ? previous?.content : deletion.content
log(`Message ${deletion.id} was deleted${typeof content === "string" ? `: "${content}"` : ""}`)
})
const purges = client.on("messageDeleteBulk", (batch, _signal, { previous }) => {
log(`${batch.ids.length} messages were deleted, ${previous?.length ?? 0} of them cached`)
})
return [edits, deletions, purges]
}
```
The snapshot is the client's own last observation, never fetched. It is `undefined` when the cache is off, never saw the entity, or already removed it, such as after an expiry, a capacity limit or a lost connection. The [`PreviousSnapshots`](https://fluxerly.neontechspace.com/docs/api/js-ts/events-and-collectors/#previoussnapshots) reference lists the events that carry one
## Wait for a community's setup
A partitioned handler's key can need its own setup before its events run, such as a community that is still loading its data after a restart. Waiting inside the handler holds one of the shared slots, so starting communities would stall every other one
The `partitionReady` option moves that wait out of the handler: The SDK calls it with the key before the first waiting event of that key starts, and the key's events stay in the queue, using no slot, until the returned promise settles. Events of other keys keep running meanwhile
```ts
import type { Client } from "@neontechspace/fluxerly"
export function afterServerSetup(client: Client, setups: Map>) {
return client.on("messageCreate", (message) => console.log(message.content), {
partition: "guild",
// A direct message has no community and is keyed by its channel, so an unknown key counts as ready
partitionReady: (key) => setups.get(key),
})
}
```
The hook is valid only together with `partition`, and in the Effect entry point it returns an Effect. A promise that never settles holds the key until the subscription closes, and a draining shutdown waits for held events until its `drainMs` passes
The SDK remembers that a key is ready only while it has waiting or running events, so the hook is called again for the next burst after the key went idle. Hooks for different keys run at the same time, so keep the hook a cheap check that answers at once when the key is ready
A hook that throws or rejects reports every waiting event of that key as a failure of its handler, and those handlers do not run. Held events count toward `maxPendingMessages`, 256 by default, so a bot that waits for many starting communities needs a larger limit
## Follow threads
Six events report [threads](https://fluxerly.neontechspace.com/docs/threads.md). The `threadCreate` event arrives when a thread is created and also when the bot joins or is added to an existing thread, so check `isNewlyCreated` to react only to new threads
```ts
import type { Client } from "@neontechspace/fluxerly"
export function welcomeNewThreads(client: Client) {
return client.on("threadCreate", (thread) =>
thread.isNewlyCreated ? client.messages.send(thread.id, `Welcome to ${thread.name}`) : undefined,
)
}
```
The other five are `threadUpdate`, with the thread after a change such as a rename, archive or lock, `threadDelete`, with the deleted thread's ID and parent, `threadListSync`, with the bot's active threads after Fluxer replaced them for a community or some of its channels, `threadMemberUpdate`, with changes to the bot's own membership of a thread, and `threadMembersUpdate`, with the accounts that joined or left a thread
Deleting a text, announcement, forum or media channel also deletes its threads, and Fluxer sends no `threadDelete` for them. To notice that, handle `guildChannelDelete` and treat every thread whose `parentId` is the deleted channel as gone
What do thread events change in the cache?
With `cache.channels` enabled, thread create and update events store the thread, a thread deletion removes it and a thread list replaces the cached threads it covers. A community's snapshot at startup also fills the cache with its active threads
When the bot's own membership of a thread changes, the SDK removes that cached thread, because its `membership` field would be out of date. Fluxer does not replay thread lists after a lost connection, so a resumed connection also removes its communities' cached threads. The [message cache](https://fluxerly.neontechspace.com/docs/history-and-cache.md#limit-the-message-cache) removes a deleted thread's messages
## Wait for one future event
Use `waitFor` to get the next matching event. The filter runs synchronously, so keep it small and do not make requests inside it
```ts
import { describeError, type Client } from "@neontechspace/fluxerly"
export async function waitForTyping(client: Client, channelId: string, userId: string) {
const result = await client.waitFor("typingStart", {
filter: (event) => event.channelId === channelId && event.userId === userId,
timeoutMs: 10_000,
})
if (result.isErr()) {
console.error(describeError(result.error))
return
}
return result.value
}
```
If no matching event arrives within 10 seconds, `waitFor` returns a failed Result. Only a future event counts, not one that already happened. To send a prompt and then wait for the answer, use a collector as shown next, because it starts listening before the prompt is sent
## Ask a question without missing a fast reply
A [collector](https://fluxerly.neontechspace.com/docs/glossary.md#collector) gathers matching messages or reactions for a limited time. Create the collector first, then send the question. This helper collects one person's next message in the channel, waiting at most 30 seconds
```ts
import { orThrow, type Client } from "@neontechspace/fluxerly"
export async function askPreferredName(client: Client, channelId: string, userId: string) {
await using collector = client.messages.collect(channelId, {
filter: (message) => message.author.id === userId && !message.author.isBot,
maxMessages: 1,
timeoutMs: 30_000,
})
orThrow(await client.messages.send(channelId, "What name should the bot use?"))
const answer = orThrow(await collector.result())
return answer.messages[0]?.content
}
```
The helper returns the reply's text, or `undefined` when no one answers in time, because a collector that times out still succeeds, possibly with no messages. The `orThrow` helper returns a successful value or throws the failure
The `await using` declaration closes the collector when the helper returns or throws, including when sending fails, and waits for its cleanup
When does a collector fail?
A [gateway gap](https://fluxerly.neontechspace.com/docs/glossary.md#gateway-gap), such as a lost connection, fails collection because messages may have been missed, and so does a client that shuts down while the collector runs. A per-message or per-reaction callback that throws fails collection with a `CollectorError` whose reason is `handler`.
Do not shut the client down or await the same collector's `result()` from inside its own callbacks
## Accept a confirmation reaction
Use an existing bot message as the target. Start this helper before inviting the person to react, and keep the client connected
```ts
import { orThrow, type Client, type MessageReference } from "@neontechspace/fluxerly"
export async function waitForConfirmation(client: Client, message: MessageReference, userId: string) {
await using collector = client.messages.collectReactions(message, {
emoji: "✅",
filter: (reaction) => reaction.userId === userId,
maxReactions: 1,
timeoutMs: 20_000,
})
const result = orThrow(await collector.result())
return result.reactions.length > 0
}
```
The helper returns `true` when the person adds ✅ within 20 seconds. It watches for new reactions, not reactions already on the message. Removing a reaction does not undo a collected one, and repeated additions are not a count of unique voters, so keep a poll's votes in application state
For a community channel, pass its known `guildId` in the collector options so recovery is limited to that community's [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard). Do not assume a channel is private merely because an event omitted community context. See the [collector reference](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-collectreactions) for buffer limits and subscription ownership
## Show pages with reactions
Fluxer has no buttons, so a long list can be shown as pages that people flip with ◀ and ▶ reactions. The `messages.paginate` method sends the first page, adds both arrows as the bot and shows the previous or next page on each click, wrapping around at the ends. Pass `users` to choose who may flip, such as `[userId]`, or `() => true` for anyone
```ts
import type { Client } from "@neontechspace/fluxerly"
export function showRules(client: Client, channelId: string, userId: string) {
return client.messages.paginate(channelId, ["Rules 1 to 5", "Rules 6 to 10"], { users: [userId] })
}
```
With several pages, the returned Result settles when listening ends, after `idleMs` without a click, 60 seconds by default, or `timeoutMs` after the first page, 5 minutes by default. The bot then removes its own arrows, and the current page stays shown. A page is text or an object with `content` and `embeds`
Adding or removing an arrow turns the page, so the bot needs only Add Reactions and Read Message History. With `removeClicks: true`, only additions count and the bot removes each click, which needs Manage Messages. Several pages need a connected gateway, while a single page is sent without a collector
In a command, the context's `paginate(pages)` lets the command's author flip by default, and `sendHelp()` sends the help pages this way. See [help in Commands](https://fluxerly.neontechspace.com/docs/commands.md#add-help-from-the-registered-commands)
## Read events in Fluxer's own form
Every dispatch also arrives as the `raw` event, with Fluxer's field names and, once `documented` is true, the payload type Fluxer's documentation describes for it. A voice join that Fluxer refuses arrives as the `gatewayError` event, which is not a dispatch and never reaches `raw`. [Raw requests and raw events](https://fluxerly.neontechspace.com/docs/raw-requests-and-events.md#read-an-event-without-a-type) shows both
## Wire it up
In a `runBot` bot, event handlers go in `events` and receive the event and the client. A collector can run inside a command, which provides the client and the incoming message. This bot logs new community joins and answers `!ask`
```ts
import { orThrow, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
onError: (report) => console.error(report.describe()),
events: {
guildCreate: ({ event }) => {
if (event.isNewJoin) console.info(`Joined guild ${event.id}`)
},
},
commands: {
prefix: "!",
commands: {
ask: {
description: "Ask for a preferred name",
execute: async ({ client, message, reply }) => {
await using collector = client.messages.collect(message.channelId, {
filter: (answer) => answer.author.id === message.author.id,
maxMessages: 1,
timeoutMs: 30_000,
})
orThrow(await reply("What name should the bot use?"))
const answer = orThrow(await collector.result()).messages[0]
return reply(answer ? `Hello, ${answer.content}!` : "No answer in time")
},
},
},
},
})
```
A failing handler or command does not stop the bot. The `onError` hook receives its report with the original error, and without the hook the SDK logs it in full at Error. By default, `messageCreate` handlers and commands run up to eight at a time and other events one at a time. The [`events` option reference](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#botoptions-events) explains how to change that per event
---
# Example bots
Small, complete bots for moderation, reaction roles, welcomes and tickets, ready to copy and run
Each example on this page is one complete file shaped like the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md)'s bot: It exports its options as `bot` with `defineBot` and passes them to `runBot` when Node.js runs the file. Copy it, set a few environment variables and run it. Every example logs failures in full and stops cleanly on Ctrl+C
Start with the [small bot](https://fluxerly.neontechspace.com/docs/small-bot.md) for a guided tour of commands, arguments, embeds, events, guards and cooldowns in one file. The examples below each solve one common task
## Run an example
Set up a project as in the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md): A folder with `"type": "module"` in `package.json` and the SDK installed. Save the example as `bot.js`, or as `bot.ts` to keep the TypeScript version, which Node.js 26 runs directly
Each example's folder on GitHub also holds its own test, `bot.test.js` or `bot.test.ts`, to use instead of the generated project's `!ping` test. It runs the example without a token or a network, as [Testing a bot](https://fluxerly.neontechspace.com/docs/testing.md) shows. Examples with required variables read them in `setup`, so their tests set them before calling `ready()`
Put the token and the example's other variables in a `.env` file, one `KEY=value` line each, and keep that file out of version control
```text
FLUXER_BOT_TOKEN=paste-the-token-here
WELCOME_CHANNEL_ID=123456789012345678
```
Start the bot with Node.js loading that file:
```sh
node --env-file=.env bot.js
```
A missing variable stops the bot at startup with an explanation. Channels, roles and messages are configured by their decimal [IDs](https://fluxerly.neontechspace.com/docs/glossary.md#id). The [deploying guide](https://fluxerly.neontechspace.com/docs/deploying.md) shows how to keep a bot running on a server
### Copy the required IDs
In Fluxer's desktop interface:
- Right-click the channel and choose **Copy channel ID**
- Right-click the target message and choose **Copy message ID**
- In the community's role settings, right-click the role and choose **Copy role ID**
- Right-click the ticket category and choose **Copy category ID**
Put each copied ID in its matching `.env` variable
### Give the bot its permissions
The invite in [Create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md#3-invite-the-bot-to-a-community) grants only what the quick start needs. Each example below lists the permissions it needs, and without them its requests fail with a missing-permissions error
For a bot that is already in the community, edit the role Fluxer created for it, which has the application's name, and turn on the listed permissions in the community's role settings. For a bot that is not in the community yet, pass the listed names to the invite script instead, for example for the moderation example:
```ts
import { links, permissionBits } from "@neontechspace/fluxerly"
const applicationId = process.argv[2] ?? ""
const permissions = permissionBits.from([
"ViewChannel",
"SendMessages",
"ReadMessageHistory",
"ModerateMembers",
"KickMembers",
"BanMembers",
"ManageMessages",
])
console.log(links.installation(applicationId, { permissions }))
```
Some examples also change roles or members. Fluxer allows that only when the bot's highest role ranks above them, so place the bot's role above those roles in the role settings
## Moderation commands
Five prefix commands for moderators:
- `!timeout @member 10m reason` stops a member from talking for 1 minute to 7 days
- `!kick @member reason` removes a member from the community
- `!ban @member reason` bans a member permanently
- `!tempban @member 7d reason` bans a member for 1 minute to 2 years
- `!clear 20` deletes up to 20 recent messages in the channel
Each reason is optional. Each command has a [guard](https://fluxerly.neontechspace.com/docs/glossary.md#guard) that checks the moderator's own permission. The `!timeout`, `!kick`, `!ban` and `!tempban` commands also check that both the moderator and the bot outrank the target member through `afterParse: guards.canManage("member")`. When a command fails, a [middleware](https://fluxerly.neontechspace.com/docs/glossary.md#middleware) function tells the moderator without showing error details in the channel
- Variables: `FLUXER_BOT_TOKEN`
- Bot permissions: `ViewChannel`, `SendMessages`, `ReadMessageHistory`, `ModerateMembers`, `KickMembers`, `BanMembers` and `ManageMessages`. The bot's highest role must also rank above the members it acts on
- Moderator permissions: `ModerateMembers` for `!timeout`, `KickMembers` for `!kick`, `BanMembers` for `!ban` and `!tempban`, and `ManageMessages` for `!clear`
- Two-factor authentication: In a community that requires it for moderation, every command fails with HTTP 400 unless the account that owns the bot's application has it enabled. See [communities that require two-factor authentication](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#communities-that-require-two-factor-authentication)
```ts
// In a server that requires two-factor authentication for moderation, Fluxer refuses these commands with
// HTTP 400 unless the account that owns the bot's application has two-factor authentication enabled
import { defineBot, describeError, format, guards, orThrow, runBot } from "@neontechspace/fluxerly"
export const bot = defineBot({
onError: (report) => console.error(report.describe()),
commands: {
prefix: "!",
use: [
// Tell the moderator when a command fails, without showing error details in the channel.
// The router still reports the full error to onError
async ({ reply }, next) => {
try {
await next()
} catch (error) {
const sent = await reply("That command failed. The error was reported")
if (sent.isErr()) console.error(describeError(sent.error))
throw error
}
},
],
commands: {
timeout: {
description: "Stop a member from talking for a while",
guard: guards.requirePermissions(["ModerateMembers"]),
arguments: {
member: { type: "member" },
duration: { type: "duration", min: 60_000, max: 7 * 24 * 60 * 60_000 },
reason: { type: "text", rest: true, optional: true },
},
// Both the moderator and the bot must outrank the target member before the action runs
afterParse: guards.canManage("member"),
execute: async ({ client, values, reply }) => {
orThrow(
await client.members.timeout(values.member, values.duration, {
timeoutReason: values.reason ?? null,
}),
)
return reply(`Timed out ${format.userMention(values.member.userId)}`)
},
},
kick: {
description: "Remove a member from the server",
guard: guards.requirePermissions(["KickMembers"]),
arguments: { member: { type: "member" }, reason: { type: "text", rest: true, optional: true } },
afterParse: guards.canManage("member"),
execute: async ({ client, values, reply }) => {
const options = values.reason === undefined ? {} : { auditReason: values.reason }
orThrow(await client.members.kick(values.member, options))
return reply(`Kicked ${format.userMention(values.member.userId)}`)
},
},
ban: {
description: "Ban a member permanently",
guard: guards.requirePermissions(["BanMembers"]),
arguments: { member: { type: "member" }, reason: { type: "text", rest: true, optional: true } },
afterParse: guards.canManage("member"),
execute: async ({ client, values, reply }) => {
const ban = values.reason === undefined ? {} : { reason: values.reason }
orThrow(await client.members.ban(values.member, ban))
return reply(`Banned ${format.userMention(values.member.userId)}`)
},
},
// A separate command keeps the duration required, so a reason word is never read as a duration
tempban: {
description: "Ban a member for a while, such as 7d",
guard: guards.requirePermissions(["BanMembers"]),
arguments: {
member: { type: "member" },
// Fluxer takes ban durations in whole seconds, from one minute up to two years
duration: { type: "duration", wholeSeconds: true, min: 60_000, max: 63_072_000_000 },
reason: { type: "text", rest: true, optional: true },
},
afterParse: guards.canManage("member"),
execute: async ({ client, values, reply }) => {
// Ban durations are milliseconds, so the bounded duration argument passes through unchanged
const ban = {
durationMs: values.duration,
...(values.reason === undefined ? {} : { reason: values.reason }),
}
orThrow(await client.members.ban(values.member, ban))
return reply(`Banned ${format.userMention(values.member.userId)} for a while`)
},
},
clear: {
description: "Delete recent messages in this channel",
guard: guards.requirePermissions(["ManageMessages"]),
cooldown: { durationMs: 10_000, per: "channel" },
arguments: { count: { type: "integer", min: 1, max: 100, default: 10 } },
execute: async ({ client, message, values, reply }) => {
// The preview lists the exact messages first, and cleanup deletes only those
const plan = orThrow(
await client.messages.previewCleanup(message.channelId, {
filter: (candidate) => candidate.id !== message.id,
maxScanned: values.count + 1,
maxSelected: values.count,
}),
)
const report = orThrow(await client.messages.cleanup(plan))
return reply(`Requested deletion of ${report.selectedMessageIds.length} messages`)
},
},
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main) await runBot({ token: process.env.FLUXER_BOT_TOKEN, ...bot })
```
Effect version
```ts
// In a server that requires two-factor authentication for moderation, Fluxer refuses these commands with
// HTTP 400 unless the account that owns the bot's application has two-factor authentication enabled
import { Effect } from "effect"
import { defineBot, describeError, format, guards, runBot } from "@neontechspace/fluxerly/effect"
export const bot = defineBot({
onError: (report) => Effect.logError(report.describe()),
commands: {
prefix: "!",
use: [
// Tell the moderator when a command fails, without showing error details in the channel.
// The router still reports the full error to onError
({ reply }, next) =>
next.pipe(
Effect.tapError(() =>
reply("That command failed. The error was reported").pipe(
Effect.catch((error) => Effect.logError(describeError(error))),
),
),
),
],
commands: {
timeout: {
description: "Stop a member from talking for a while",
guard: guards.requirePermissions(["ModerateMembers"]),
arguments: {
member: { type: "member" },
duration: { type: "duration", min: 60_000, max: 7 * 24 * 60 * 60_000 },
reason: { type: "text", rest: true, optional: true },
},
// Both the moderator and the bot must outrank the target member before the action runs
afterParse: guards.canManage("member"),
execute: ({ client, values, reply }) =>
Effect.gen(function* () {
yield* client.members.timeout(values.member, values.duration, {
timeoutReason: values.reason ?? null,
})
return yield* reply(`Timed out ${format.userMention(values.member.userId)}`)
}),
},
kick: {
description: "Remove a member from the server",
guard: guards.requirePermissions(["KickMembers"]),
arguments: { member: { type: "member" }, reason: { type: "text", rest: true, optional: true } },
afterParse: guards.canManage("member"),
execute: ({ client, values, reply }) =>
Effect.gen(function* () {
const options = values.reason === undefined ? {} : { auditReason: values.reason }
yield* client.members.kick(values.member, options)
return yield* reply(`Kicked ${format.userMention(values.member.userId)}`)
}),
},
ban: {
description: "Ban a member permanently",
guard: guards.requirePermissions(["BanMembers"]),
arguments: { member: { type: "member" }, reason: { type: "text", rest: true, optional: true } },
afterParse: guards.canManage("member"),
execute: ({ client, values, reply }) =>
Effect.gen(function* () {
const ban = values.reason === undefined ? {} : { reason: values.reason }
yield* client.members.ban(values.member, ban)
return yield* reply(`Banned ${format.userMention(values.member.userId)}`)
}),
},
// A separate command keeps the duration required, so a reason word is never read as a duration
tempban: {
description: "Ban a member for a while, such as 7d",
guard: guards.requirePermissions(["BanMembers"]),
arguments: {
member: { type: "member" },
// Fluxer takes ban durations in whole seconds, from one minute up to two years
duration: { type: "duration", wholeSeconds: true, min: 60_000, max: 63_072_000_000 },
reason: { type: "text", rest: true, optional: true },
},
afterParse: guards.canManage("member"),
execute: ({ client, values, reply }) =>
Effect.gen(function* () {
// Ban durations are milliseconds, so the bounded duration argument passes through unchanged
const ban = {
durationMs: values.duration,
...(values.reason === undefined ? {} : { reason: values.reason }),
}
yield* client.members.ban(values.member, ban)
return yield* reply(`Banned ${format.userMention(values.member.userId)} for a while`)
}),
},
clear: {
description: "Delete recent messages in this channel",
guard: guards.requirePermissions(["ManageMessages"]),
cooldown: { durationMs: 10_000, per: "channel" },
arguments: { count: { type: "integer", min: 1, max: 100, default: 10 } },
execute: ({ client, message, values, reply }) =>
Effect.gen(function* () {
// The preview lists the exact messages first, and cleanup deletes only those
const plan = yield* client.messages.previewCleanup(message.channelId, {
filter: (candidate) => candidate.id !== message.id,
maxScanned: values.count + 1,
maxSelected: values.count,
})
const report = yield* client.messages.cleanup(plan)
return yield* reply(`Requested deletion of ${report.selectedMessageIds.length} messages`)
}),
},
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main)
await Effect.runPromiseExit(runBot({ token: process.env.FLUXER_BOT_TOKEN, processSignals: true, ...bot }))
```
The `!clear` command previews the exact messages first and then deletes only those. The reply reports how many deletions were requested, because Fluxer confirms each batch rather than each message. See [the source on GitHub](https://github.com/NeonTechSpace/Fluxerly.js/tree/main/projects/sdk/examples/moderation)
## Reaction roles
Members react to one existing message to receive an opt-in role, and remove their reaction to give it back. At startup, the bot checks that it ranks above the role and adds the emoji to the message itself, so members can see which one to use
- Variables: `FLUXER_BOT_TOKEN`, `ROLE_CHANNEL_ID` and `ROLE_MESSAGE_ID` for the message, `ROLE_ID` for the role, and an optional `ROLE_EMOJI`, a Unicode emoji that defaults to ✅
- Bot permissions: `ViewChannel`, `ReadMessageHistory`, `AddReactions` and `ManageRoles`. The bot's highest role must rank above the configured role
```ts
import { defineBot, orThrow, runBot } from "@neontechspace/fluxerly"
function requiredEnv(name: string) {
const value = process.env[name]
if (!value) throw new Error(`Set the ${name} environment variable`)
return value
}
const emoji = process.env.ROLE_EMOJI || "✅"
export const bot = defineBot({
onError: (report) => console.error(report.describe()),
// Check the configuration once before connecting, so a missing setting or a role the bot cannot assign stops it
// at startup
setup: async (client) => {
const target = { channelId: requiredEnv("ROLE_CHANNEL_ID"), id: requiredEnv("ROLE_MESSAGE_ID") }
const roleId = requiredEnv("ROLE_ID")
const { guildId } = orThrow(await client.channels.fetch(target.channelId))
if (!orThrow(await client.roles.fetchCanManage({ guildId, id: roleId })))
throw new Error("ROLE_ID must name a role below the bot's highest role")
// The bot's own reaction shows members which emoji to use
orThrow(await client.messages.addReaction(target, emoji))
// One shared subscription keeps adds and removals for the same member in arrival order
client.onMany(
["messageReactionAdd", "messageReactionRemove"],
({ event, payload }) => {
if (payload.id !== target.id || payload.emoji.name !== emoji) return
if (payload.userId === client.users.getSelf()?.id) return
const member = { guildId, userId: payload.userId }
return event === "messageReactionAdd"
? client.members.addRole(member, roleId)
: client.members.removeRole(member, roleId)
},
{ partition: ({ payload }) => payload.userId },
)
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main) await runBot({ token: process.env.FLUXER_BOT_TOKEN, ...bot })
```
Effect version
```ts
import { Data, Effect } from "effect"
import { defineBot, runBot } from "@neontechspace/fluxerly/effect"
// A missing or wrong setting fails setup, which stops the bot at startup with this message
class SettingError extends Data.TaggedError("SettingError")<{ readonly message: string }> {}
const requiredEnv = (name: string) =>
Effect.suspend(() => {
const value = process.env[name]
return value ? Effect.succeed(value) : new SettingError({ message: `Set the ${name} environment variable` })
})
const emoji = process.env.ROLE_EMOJI || "✅"
export const bot = defineBot({
onError: (report) => Effect.logError(report.describe()),
// Check the configuration once before connecting, so a missing setting or a role the bot cannot assign stops it
// at startup
setup: (client) =>
Effect.gen(function* () {
const target = {
channelId: yield* requiredEnv("ROLE_CHANNEL_ID"),
id: yield* requiredEnv("ROLE_MESSAGE_ID"),
}
const roleId = yield* requiredEnv("ROLE_ID")
const { guildId } = yield* client.channels.fetch(target.channelId)
if (!(yield* client.roles.fetchCanManage({ guildId, id: roleId })))
return yield* new SettingError({ message: "ROLE_ID must name a role below the bot's highest role" })
// The bot's own reaction shows members which emoji to use
yield* client.messages.addReaction(target, emoji)
// One shared subscription keeps adds and removals for the same member in arrival order
yield* client.onMany(
["messageReactionAdd", "messageReactionRemove"],
({ event, payload }) =>
Effect.gen(function* () {
if (payload.id !== target.id || payload.emoji.name !== emoji) return
const self = yield* client.users.getSelf()
if (payload.userId === self?.id) return
const member = { guildId, userId: payload.userId }
if (event === "messageReactionAdd") yield* client.members.addRole(member, roleId)
else yield* client.members.removeRole(member, roleId)
}),
{ partition: ({ payload }) => payload.userId },
)
}),
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main)
await Effect.runPromiseExit(runBot({ token: process.env.FLUXER_BOT_TOKEN, processSignals: true, ...bot }))
```
Configure only a role that members may give themselves. The bot sees only reactions made while it runs, so a member who reacted while it was offline removes the reaction and adds it again. See [the source on GitHub](https://github.com/NeonTechSpace/Fluxerly.js/tree/main/projects/sdk/examples/reaction-roles) and [communities and permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md) for more about role hierarchy
## Welcome messages
The bot greets each new member in a configured channel with a mention and an embed, and can also give every new member a starter role. It ignores joins in other communities and joining bots
- Variables: `FLUXER_BOT_TOKEN`, `WELCOME_CHANNEL_ID`, and an optional `WELCOME_ROLE_ID` for the starter role
- Bot permissions: `ViewChannel`, `SendMessages` and `EmbedLinks` in the welcome channel, plus `ManageRoles` when `WELCOME_ROLE_ID` is set. The bot's highest role must then rank above the starter role
```ts
import { builders, defineBot, format, orThrow, runBot } from "@neontechspace/fluxerly"
function requiredEnv(name: string) {
const value = process.env[name]
if (!value) throw new Error(`Set the ${name} environment variable`)
return value
}
// Optional role that every new member receives
const roleId = process.env.WELCOME_ROLE_ID || undefined
// Setup reads the channel, so a test can import this file without the setting
let channelId = ""
let guildId = ""
export const bot = defineBot({
onError: (report) => console.error(report.describe()),
// Setup runs before the bot connects, so a missing or wrong channel ID stops the bot at startup
setup: async (client) => {
channelId = requiredEnv("WELCOME_CHANNEL_ID")
guildId = orThrow(await client.channels.fetch(channelId)).guildId
},
events: {
guildMemberAdd: async ({ event: member, client }) => {
if (member.guildId !== guildId || member.isBot) return
const embed = builders
.embed()
.title("Welcome!")
.description("Read the rules, pick a nickname and say hello")
.color(0x8b7cf8)
orThrow(
await client.messages.send(channelId, {
content: `Welcome, ${format.userMention(member.userId)}!`,
embeds: [embed],
// Mentions notify nobody unless allowed explicitly
allowedMentions: { users: [member.userId] },
}),
)
if (roleId === undefined) return
// Returning the Result reports a failed role grant to onError
return client.members.addRole({ guildId, userId: member.userId }, roleId)
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main) await runBot({ token: process.env.FLUXER_BOT_TOKEN, ...bot })
```
Effect version
```ts
import { Data, Effect } from "effect"
import { builders, defineBot, format, runBot } from "@neontechspace/fluxerly/effect"
// A missing or wrong setting fails setup, which stops the bot at startup with this message
class SettingError extends Data.TaggedError("SettingError")<{ readonly message: string }> {}
const requiredEnv = (name: string) =>
Effect.suspend(() => {
const value = process.env[name]
return value ? Effect.succeed(value) : new SettingError({ message: `Set the ${name} environment variable` })
})
// Optional role that every new member receives
const roleId = process.env.WELCOME_ROLE_ID || undefined
// Setup reads the channel, so a test can import this file without the setting
let channelId = ""
let guildId = ""
export const bot = defineBot({
onError: (report) => Effect.logError(report.describe()),
// Setup runs before the bot connects, so a missing or wrong channel ID stops the bot at startup
setup: (client) =>
Effect.gen(function* () {
channelId = yield* requiredEnv("WELCOME_CHANNEL_ID")
guildId = (yield* client.channels.fetch(channelId)).guildId
}),
events: {
guildMemberAdd: ({ event: member, client }) =>
Effect.gen(function* () {
if (member.guildId !== guildId || member.isBot) return
const embed = builders
.embed()
.title("Welcome!")
.description("Read the rules, pick a nickname and say hello")
.color(0x8b7cf8)
yield* client.messages.send(channelId, {
content: `Welcome, ${format.userMention(member.userId)}!`,
embeds: [embed],
// Mentions notify nobody unless allowed explicitly
allowedMentions: { users: [member.userId] },
})
if (roleId === undefined) return
// A failed role grant fails the handler, which reports it to onError
yield* client.members.addRole({ guildId, userId: member.userId }, roleId)
}),
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main)
await Effect.runPromiseExit(runBot({ token: process.env.FLUXER_BOT_TOKEN, processSignals: true, ...bot }))
```
A welcome message that was sent but whose role grant failed stays posted, and the failure is logged. See [the source on GitHub](https://github.com/NeonTechSpace/Fluxerly.js/tree/main/projects/sdk/examples/welcome) and [events and collectors](https://fluxerly.neontechspace.com/docs/events-and-collectors.md) for more about member and community events
## Support tickets
A member sends `!ticket` to open a private channel visible to them, the staff role, the bot, the community owner and members with `Administrator`. Anyone in that channel sends `!close` to delete it. Each member has at most one open ticket, and a [cooldown](https://fluxerly.neontechspace.com/docs/glossary.md#cooldown) allows one `!ticket` per member per minute
- Variables: `FLUXER_BOT_TOKEN`, `TICKET_CATEGORY_ID` for the category that holds tickets, and `TICKET_STAFF_ROLE_ID` for the role that answers them
- Bot permissions: `ManageChannels` and `ManageRoles`, plus `ViewChannel`, `SendMessages` and `ReadMessageHistory` in the ticket category. Fluxer lets the bot grant only permissions it has itself
```ts
import { ChannelType, defineBot, format, guards, orThrow, permissionBits, runBot } from "@neontechspace/fluxerly"
function requiredEnv(name: string) {
const value = process.env[name]
if (!value) throw new Error(`Set the ${name} environment variable`)
return value
}
const access = permissionBits.from(["ViewChannel", "SendMessages", "ReadMessageHistory"])
// Setup reads the required settings, so a test can import this file without them
let categoryId = ""
let staffRoleId = ""
export const bot = defineBot({
onError: (report) => console.error(report.describe()),
// Setup runs before the bot connects, so a missing setting stops the bot at startup
setup: () => {
categoryId = requiredEnv("TICKET_CATEGORY_ID")
staffRoleId = requiredEnv("TICKET_STAFF_ROLE_ID")
},
commands: {
prefix: "!",
commands: {
ticket: {
description: "Open a private channel with the staff",
guard: guards.guildOnly(),
// One attempt per member per minute, and the name check below keeps one open ticket per member
cooldown: { durationMs: 60_000, per: "user" },
execute: async ({ client, message, reply }) => {
const { guildId } = message
const name = `ticket-${message.author.id}`
const channels = orThrow(await client.channels.fetchAll(guildId))
const open = channels.find((channel) => channel.parentId === categoryId && channel.name === name)
if (open) return reply(`A ticket is already open: ${format.channelMention(open.id)}`)
// The bot's own account, as Fluxer reported it when the bot connected, read without a request
const bot = client.users.getSelf()
if (bot === undefined) return reply("The bot's own account is not known yet. Try again later")
const channel = orThrow(
await client.channels.create(guildId, {
type: ChannelType.Text,
name,
parentId: categoryId,
// Hide the channel from other members. The member, the staff role and the bot can see it, as can the owner and Administrators
permissionOverwrites: [
permissionBits.overwrite({ id: guildId, type: "role", deny: ["ViewChannel"] }),
permissionBits.overwrite({ id: staffRoleId, type: "role", allow: access }),
permissionBits.overwrite({ id: message.author.id, type: "member", allow: access }),
permissionBits.overwrite({ id: bot.id, type: "member", allow: access }),
],
}),
)
orThrow(
await client.messages.send(channel.id, {
content: `${format.userMention(message.author.id)} Describe the problem here. Send !close when it is solved`,
allowedMentions: { users: [message.author.id] },
}),
)
return reply(`Ticket opened: ${format.channelMention(channel.id)}`)
},
},
close: {
description: "Delete this ticket channel",
guard: guards.guildOnly(),
execute: async ({ client, message, reply }) => {
const channel = orThrow(await client.channels.fetch(message.channelId))
// Only channels in the ticket category that follow the ticket naming can be deleted
if (channel.parentId !== categoryId || !channel.name?.startsWith("ticket-"))
return reply("Send !close inside a ticket channel")
return client.channels.delete(channel.id)
},
},
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main) await runBot({ token: process.env.FLUXER_BOT_TOKEN, ...bot })
```
Effect version
```ts
import { Data, Effect } from "effect"
import { ChannelType, defineBot, format, guards, permissionBits, runBot } from "@neontechspace/fluxerly/effect"
// A missing or wrong setting fails setup, which stops the bot at startup with this message
class SettingError extends Data.TaggedError("SettingError")<{ readonly message: string }> {}
const requiredEnv = (name: string) =>
Effect.suspend(() => {
const value = process.env[name]
return value ? Effect.succeed(value) : new SettingError({ message: `Set the ${name} environment variable` })
})
const access = permissionBits.from(["ViewChannel", "SendMessages", "ReadMessageHistory"])
// Setup reads the required settings, so a test can import this file without them
let categoryId = ""
let staffRoleId = ""
export const bot = defineBot({
onError: (report) => Effect.logError(report.describe()),
// Setup runs before the bot connects, so a missing setting stops the bot at startup
setup: () =>
Effect.gen(function* () {
categoryId = yield* requiredEnv("TICKET_CATEGORY_ID")
staffRoleId = yield* requiredEnv("TICKET_STAFF_ROLE_ID")
}),
commands: {
prefix: "!",
commands: {
ticket: {
description: "Open a private channel with the staff",
guard: guards.guildOnly(),
// One attempt per member per minute, and the name check below keeps one open ticket per member
cooldown: { durationMs: 60_000, per: "user" },
execute: ({ client, message, reply }) =>
Effect.gen(function* () {
const { guildId } = message
const name = `ticket-${message.author.id}`
const channels = yield* client.channels.fetchAll(guildId)
const open = channels.find(
(channel) => channel.parentId === categoryId && channel.name === name,
)
if (open) return yield* reply(`A ticket is already open: ${format.channelMention(open.id)}`)
// The bot's own account, as Fluxer reported it when the bot connected, read without a request
const bot = yield* client.users.getSelf()
if (bot === undefined)
return yield* reply("The bot's own account is not known yet. Try again later")
const channel = yield* client.channels.create(guildId, {
type: ChannelType.Text,
name,
parentId: categoryId,
// Hide the channel from other members. The member, the staff role and the bot can see it, as can the owner and Administrators
permissionOverwrites: [
permissionBits.overwrite({ id: guildId, type: "role", deny: ["ViewChannel"] }),
permissionBits.overwrite({ id: staffRoleId, type: "role", allow: access }),
permissionBits.overwrite({ id: message.author.id, type: "member", allow: access }),
permissionBits.overwrite({ id: bot.id, type: "member", allow: access }),
],
})
yield* client.messages.send(channel.id, {
content: `${format.userMention(message.author.id)} Describe the problem here. Send !close when it is solved`,
allowedMentions: { users: [message.author.id] },
})
return yield* reply(`Ticket opened: ${format.channelMention(channel.id)}`)
}),
},
close: {
description: "Delete this ticket channel",
guard: guards.guildOnly(),
execute: ({ client, message, reply }) =>
Effect.gen(function* () {
const channel = yield* client.channels.fetch(message.channelId)
// Only channels in the ticket category that follow the ticket naming can be deleted
if (channel.parentId !== categoryId || !channel.name?.startsWith("ticket-"))
return yield* reply("Send !close inside a ticket channel")
return yield* client.channels.delete(channel.id)
}),
},
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main)
await Effect.runPromiseExit(runBot({ token: process.env.FLUXER_BOT_TOKEN, processSignals: true, ...bot }))
```
The bot reads its own user ID with `client.users.getSelf()`, which returns the account Fluxer reported when the bot connected, without a request. The `!close` command deletes only channels in the ticket category whose names start with `ticket-`. See [the source on GitHub](https://github.com/NeonTechSpace/Fluxerly.js/tree/main/projects/sdk/examples/tickets) and [commands](https://fluxerly.neontechspace.com/docs/commands.md) for more about guards and cooldowns
---
# Frequently asked questions
Short answers to common questions about the SDK
Each answer is short and links to the page that covers the topic in full
## Why does loading the SDK fail with a require error?
The SDK ships only ECMAScript modules, so `require("@neontechspace/fluxerly")` fails with an error saying that Fluxerly is ESM-only. Use `import`, and add `"type": "module"` to the project's `package.json` or name the file with `.mjs`. See [troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md#the-process-fails-with-a-require-error)
## Does Fluxerly support voice?
For gateway signaling and member controls, yes. Today `client.voice` handles joining, leaving, voice state updates and typed voice grants (`voiceServerUpdate`), signals (`voiceSignal`), states (`voiceStateUpdate`) and refusals (`gatewayError`) cleanly while keeping `gateway.ignoredEvents: "auto"` active, alongside member voice controls, voice notes and audio or video attachments. Built-in audio transport and playback are planned for Fluxer's own voice engine so bots avoid lock-in to a temporary media layer, and bots needing audio today can pass the typed grant straight to their own media client. See [voice controls and signaling](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#voice-controls-versus-a-voice-connection)
## Which Node.js version is required?
Fluxerly needs Node.js 26.13 or newer and checks the version when runtime entry points load, while `fluxerly doctor` and `fluxerly triage` still run on older releases so they can report the version check cleanly. A bot runs as a Node.js program on a computer or server, not inside a web page. See [support and compatibility](https://fluxerly.neontechspace.com/docs/support-and-compatibility.md)
## Does TypeScript need extra setup?
Install `@types/node` as a development dependency and include the Node.js types, for example with `"types": ["node"]` in `tsconfig.json`. The SDK's types use Node.js `AbortSignal` and `AsyncDisposable`. The SDK supports TypeScript 7. JavaScript projects need no TypeScript installation. See the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md), under **Using TypeScript or Effect?**
## Where should the bot token be stored?
Keep it out of the code, in the `FLUXER_BOT_TOKEN` environment variable. For local development, put it in a `.env` file, start the bot with `node --env-file=.env bot.js`, and add `.env` to `.gitignore`. The SDK never writes the token to its logs. Regenerate a token that has been shared or committed. See [create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md)
## Why does the bot not see or answer messages?
The bot must be a member of the community and have permission to view the channel and send messages there. [Create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md) lists the minimum permissions. The SDK sends no gateway intents, so no intent setting is required. The `gateway.ignoredEvents` option suppresses listed dispatches, with exceptions for messages that mention the bot, @here or @everyone, and for reaction batches. See [event filtering](https://fluxerly.neontechspace.com/docs/testing.md#match-gateway-event-filtering) for those exceptions. The starter also ignores messages from bots and anything other than `!ping`. See [troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md#no-reply-arrives)
## Why do methods return Results instead of throwing?
Failures such as a missing permission, a network error or a rate limit are expected in a running bot. A [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) makes them visible in the return type, so they are handled where they happen instead of stopping the bot. Invalid options still throw `ConfigurationError` at once, while invalid request input comes back as a failed Result. The `orThrow` function returns a Result's value or throws its error when throwing suits the code better. See [reliability](https://fluxerly.neontechspace.com/docs/reliability.md)
## What is Effect?
Effect is a TypeScript library for writing programs that handle failures, cancellation and cleanup in a structured way. Work is written as an Effect value that describes what to do, and each possible failure is part of its type. When the work stops, whether it succeeded, failed or was cancelled, Effect runs the cleanup it owns. The [Effect website](https://effect.website) introduces it
## Is Effect required?
No. The default `@neontechspace/fluxerly` entry point works with plain JavaScript or TypeScript, Promises and Results. The SDK uses Effect internally, and npm, pnpm and Bun install it automatically. The `@neontechspace/fluxerly/effect` entry point is for applications that already use Effect. See [first Effect bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md)
## Does the bot need to handle rate limits?
Usually not. For Fluxer API requests, an HTTP 429 with a usable retry delay is retried when the request body can be reused and the wait fits within the request's deadline. An inline attachment or webhook request carrying a `file` or `stream` attachment fails instead, because that body cannot be sent again
A response without a usable retry delay also fails. Waits of a second or longer are logged as `ratelimit.wait`. For a request whose body can be reused, a known wait that would reach or pass its deadline fails with a `ratelimit.deadline` record instead. See [rate limit](https://fluxerly.neontechspace.com/docs/glossary.md#rate-limit) and [troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md)
## How can a bot be tested without Fluxer?
The `@neontechspace/fluxerly/testing` entry point creates a real client connected to an in-memory Fluxer. Its `createTestBot` function runs a bot from the same options object it passes to `runBot`. Tests deliver events, answer requests and check what the bot sent, without a network, token or account. Effect applications use `@neontechspace/fluxerly/effect/testing`. See [Test a bot without Fluxer](https://fluxerly.neontechspace.com/docs/testing.md)
## Does the bot need sharding?
Most bots do not. One [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard) carries up to 2,500 communities, Fluxer's limit. For a larger bot in one process, `sharding: "auto"` counts its communities when it first connects and opens one shard per 2,000 communities, which leaves room to grow
A bot without `sharding` settings that passes the limit moves to that automatic count when Fluxer refuses its one shard, so it keeps running. Running shards in several processes without a supervisor needs an explicit shard total. A [supervisor](https://fluxerly.neontechspace.com/docs/sharding.md#run-shards-in-several-processes) can choose the total itself with `totalShards: "auto"`. See [sharding](https://fluxerly.neontechspace.com/docs/sharding.md)
---
# Create and manage forum channels
Recognize forum and media channels, create them with tags and post settings, change one tag at a time and read their posts
A forum channel holds posts instead of messages. Each post is a public thread with its own first message. A media channel is a forum channel that can also hide media download options
The examples use the default API. The Effect entry point exports the same names
## Recognize a forum channel
Compare `type` with `ChannelType.Forum` or `ChannelType.Media`. Both shapes share the post settings below, and only a forum channel has `defaultForumLayout`
```ts
import { ChannelFlags, ChannelType, type GuildChannel } from "@neontechspace/fluxerly"
export function forumSummary(channel: GuildChannel) {
if (channel.type !== ChannelType.Forum && channel.type !== ChannelType.Media) return undefined
return {
guidelines: channel.topic,
tags: (channel.availableTags ?? []).map((tag) => tag.name),
requiresTag: ((channel.flags ?? 0) & ChannelFlags.RequireTag) !== 0,
}
}
```
The `channels.fetchAll` method lists forum and media channels but never their posts. The `channels.fetch` method returns a post as a thread shape when the ID names one, and `channels.get` can return one when the cache holds it, so compare `type` or use `isThreadChannel` before reading fields that only some shapes have
## Read post settings
Fluxer leaves the post settings out of some payloads, such as the `guildChannelDelete` event. Each setting is therefore optional, and its absence means that it is unavailable, not that it has its default
- `availableTags`: The tags a post can carry, at most 20. Only members who can manage threads may apply or remove a `moderated` tag
- `defaultReactionEmoji`: The reaction the Fluxer app shows on each post, or null
- `defaultSortOrder`: A `ForumSortOrder` value, or null
- `defaultForumLayout`: A `ForumLayout` value, on a forum channel only
- `defaultTagSetting`: How a post search matches tags, `"match_some"` or `"match_all"`
- `defaultAutoArchiveMinutes` and `defaultThreadRateLimitPerUser`: Defaults for new posts. Fluxer stores the archive period but does not apply it to a new post
- `flags`: `ChannelFlags.RequireTag`, and `ChannelFlags.HideMediaDownloadOptions` on a media channel
Flag bits, sort orders, layouts and tag settings that this SDK version does not name are kept as Fluxer sent them. Audit-log entries for forum channel changes record `available_tags` as `ForumTag` values and `default_reaction_emoji` as a `ForumDefaultReaction`
## Read posts
Each post is a `GuildPublicThreadChannel` whose `parentId` is the forum or media channel. The `appliedTagIds` field lists the post's tags, and `ChannelFlags.Pinned` in `flags` marks the channel's pinned post. [Read threads](https://fluxerly.neontechspace.com/docs/threads.md) covers the fields every thread shares
```ts
import { ChannelType, type GuildForumChannel, type GuildThreadChannel } from "@neontechspace/fluxerly"
export function postTagNames(forum: GuildForumChannel, post: GuildThreadChannel) {
if (post.type !== ChannelType.PublicThread || post.parentId !== forum.id) return []
const names = new Map((forum.availableTags ?? []).map((tag) => [tag.id, tag.name]))
return (post.appliedTagIds ?? []).map((id) => names.get(id) ?? id)
}
```
To read the creator and first message of up to 100 posts in one call, pass their IDs to [`threads.fetchPostData`](https://fluxerly.neontechspace.com/docs/api/js-ts/channels/#threads-fetchpostdata)
## Create a forum or media channel
A `channels.create` call takes `ChannelType.Forum` or `ChannelType.Media` together with the channel's tags and post settings. The bot needs `ManageChannels`
```ts
import { ChannelFlags, ChannelType, ForumLayout, ForumSortOrder, type Client } from "@neontechspace/fluxerly"
export async function createHelpForum(client: Client, guildId: string) {
const result = await client.channels.create(guildId, {
type: ChannelType.Forum,
name: "help",
topic: "Ask one question per post and say what was already tried",
availableTags: [
{ name: "bug", emojiName: "🐛" },
{ name: "question" },
{ name: "staff", moderated: true },
],
defaultSortOrder: ForumSortOrder.CreationTime,
defaultForumLayout: ForumLayout.List,
flags: ChannelFlags.RequireTag,
})
return result.map((channel) => channel.id)
}
```
These settings are specific to forum and media channels, and the SDK rejects a setting that the created channel type cannot have before it sends anything
- `topic`: Posting guidelines of up to 4,096 characters, where other channels allow 1,024
- `availableTags`: Up to 20 tags. A tag has a `name` of 1 to 50 characters that no other tag of the channel uses, an optional `moderated` flag, and at most one of `emojiId`, a custom emoji of the community, and `emojiName`, a single Unicode emoji
- `defaultReactionEmoji`: The reaction on each post, with the same two emoji fields
- `defaultSortOrder`, `defaultForumLayout` and `defaultTagSetting`: The defaults that `ForumSortOrder`, `ForumLayout` and the tag setting names describe. A media channel has no layout
- `flags`: `ChannelFlags.RequireTag` makes every post carry a tag, which needs at least one tag that is not `moderated`. `ChannelFlags.HideMediaDownloadOptions` is valid on a media channel only
## Set thread defaults on any thread parent
Text, announcement, forum and media channels accept `defaultAutoArchiveMinutes`, one of the `ThreadAutoArchiveMinutes` values, and `defaultThreadRateLimitPerUser`, a slowmode in seconds from 0 to 21,600. A new thread copies the slowmode when its creation sets none. Fluxer stores the archive period but does not apply it, so a new thread uses `ThreadAutoArchiveMinutes.ThreeDays` unless its creation sets another period. Pass null to clear a default
## Change a forum channel
A `channels.edit` call accepts the same settings as creation, and it leaves every omitted setting unchanged. Passing null resets `defaultReactionEmoji`, `defaultSortOrder`, `defaultForumLayout` and `defaultTagSetting`. The `flags` value replaces all flags, so include `ChannelFlags.RequireTag` to keep it
The `availableTags` list replaces the whole tag list. An entry with an `id` keeps that tag and replaces its settings, an entry without one adds a tag, and a tag left out is deleted, after which posts stop showing it. A received `ForumTag` is valid input, so passing back `forum.availableTags` keeps every tag. An edit cannot see the channel's type, so Fluxer ignores a setting that does not belong to it, such as `availableTags` sent for a text channel
## Change one tag
Changing a single tag through a full list risks overwriting a concurrent change. The `channels.createForumTag`, `channels.editForumTag` and `channels.deleteForumTag` methods change one tag and return the updated channel. Each needs `ManageChannels` and accepts an `auditReason`
```ts
import type { Client, GuildForumChannel } from "@neontechspace/fluxerly"
export async function addTag(client: Client, forumId: string, name: string) {
const updated = await client.channels.createForumTag(forumId, { name })
return updated.map((channel) => channel.availableTags?.find((tag) => tag.name === name)?.id)
}
export async function moderateTag(client: Client, forum: GuildForumChannel, tagName: string) {
const tag = forum.availableTags?.find((candidate) => candidate.name === tagName)
if (tag === undefined) return undefined
// Editing a tag replaces all of its settings, so the received tag supplies the ones that stay
return await client.channels.editForumTag(forum.id, tag.id, { ...tag, moderated: true })
}
export async function removeTag(client: Client, forumId: string, tagId: string) {
return await client.channels.deleteForumTag(forumId, tagId)
}
```
Fluxer assigns the ID of a new tag, so read it from the returned channel by name. An edit without `moderated` or an emoji resets them to false or none. Deleting an unknown tag fails, which includes a second delete of the same tag. Fluxer also rejects a change that would leave a channel with `ChannelFlags.RequireTag` without a tag that is not moderated
## Start posts
[Read threads](https://fluxerly.neontechspace.com/docs/threads.md) covers posts started with the bot. A webhook that belongs to a forum or media channel can start a post with `threadName`, as the [webhook guide](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md#post-into-threads-and-forum-channels) shows
---
# Glossary
Short definitions of the terms used across the guides
Each term has a short definition and a link to the guide or reference page that covers it in more detail
## C
### Cache
A cache is a local copy of Fluxer data that the client keeps up to date from gateway events, so a lookup needs no request. Caching is off until it is enabled in the client options, and each lookup returns a [frozen snapshot](https://fluxerly.neontechspace.com/docs/glossary.md#frozen-snapshot). See [Configuration](https://fluxerly.neontechspace.com/docs/configuration.md#cache) for every cache category and [History and cache](https://fluxerly.neontechspace.com/docs/history-and-cache.md) for the message cache
### Cancellation signal
A cancellation signal is an `AbortSignal` that asks running work to stop and clean up. A `client.on` handler receives one that is aborted when its subscription closes or the client shuts down, and methods that take request options accept one as `signal`. Aborting cannot undo a change Fluxer already received. See [Reliability](https://fluxerly.neontechspace.com/docs/reliability.md#set-a-request-deadline-and-allow-cancellation)
### Channel
A channel is a place where messages are sent: A text or voice channel in a [community](https://fluxerly.neontechspace.com/docs/glossary.md#guild), or a direct conversation. Most message methods take a channel ID. See [Messages](https://fluxerly.neontechspace.com/docs/messages.md)
### Client
A client is the SDK object that sends requests to Fluxer for a bot, a webhook or an OAuth application. The bot's client also holds its token, its gateway connection and everything the bot has registered. The `runBot` function creates and runs one from the bot's options, and `createClient` returns one without connecting it. See [Core concepts](https://fluxerly.neontechspace.com/docs/core-concepts.md#the-client)
### Collector
A collector gathers future messages or reactions that pass a filter, up to a count or a time limit, and then returns them together. Register it before sending the prompt it waits for, so a fast reply is not missed. See [Events and collectors](https://fluxerly.neontechspace.com/docs/events-and-collectors.md)
### Command router
A command router reads each new message, finds the [prefix command](https://fluxerly.neontechspace.com/docs/glossary.md#prefix-command) it names, converts its arguments and runs that command. Create one with `commands.create`, or pass a `commands` option to `runBot`. See [Commands](https://fluxerly.neontechspace.com/docs/commands.md)
### Cooldown
A cooldown stops a command from running again too soon for the same user, channel or community. Set it with the command's `cooldown` option. See [Commands](https://fluxerly.neontechspace.com/docs/commands.md#guard-limit-and-wrap-commands)
## D
### Duration options
Options whose names end in `Ms`, such as `timeoutMs` and `durationMs`, are measured in milliseconds. For example, `30_000` means 30 seconds. See [Reliability](https://fluxerly.neontechspace.com/docs/reliability.md#set-a-request-deadline-and-allow-cancellation) for request deadlines
## E
### Effect
Effect is a TypeScript library for describing work, its expected errors and the services it needs. The optional `@neontechspace/fluxerly/effect` entry point returns Effects instead of Promises. Bots do not need it. See [First Effect bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md)
### Embed
An embed is a card attached to a message, with a title, description, fields, images and a color. Pass embeds in a message's `embeds` array. See [Messages](https://fluxerly.neontechspace.com/docs/messages.md#build-an-embed)
### Event
An event is a notification that Fluxer sends through the [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway), such as `messageCreate` for a new message or `guildMemberAdd` for a member joining. The SDK checks and converts each event before passing it to [handlers](https://fluxerly.neontechspace.com/docs/glossary.md#handler). See [Events and collectors](https://fluxerly.neontechspace.com/docs/events-and-collectors.md)
### Exit
An Exit is Effect's record of how a program ended: Either its value, or a Cause that describes why it failed or was interrupted. Passing `exit.cause` to `describeError` prints that reason. See [the Effect bot guide](https://fluxerly.neontechspace.com/docs/effect-first-bot.md)
## F
### Finalizer
A finalizer is a cleanup action that Effect runs and waits for when work ends, whether it succeeded, failed or was interrupted. The Effect entry point uses finalizers to close clients, subscriptions and collectors. See [Effect workflows](https://fluxerly.neontechspace.com/docs/effect-workflows.md)
### Fixture
A fixture is a ready-made Fluxer payload, such as a message or a member, for tests. A test client's `fixtures` builders return them. See [Testing](https://fluxerly.neontechspace.com/docs/testing.md)
### Frozen snapshot
A frozen snapshot is a read-only copy of Fluxer data that does not change when the data changes on Fluxer. Messages, members and cache lookups are snapshots, so read or fetch again for current data. See [History and cache](https://fluxerly.neontechspace.com/docs/history-and-cache.md)
## G
### Gateway
The gateway is the live WebSocket connection that carries [events](https://fluxerly.neontechspace.com/docs/glossary.md#event) from Fluxer to the bot. The client opens it with `connect()` or `run()`, and `runBot` opens it automatically. Sending messages and most other actions use [REST](https://fluxerly.neontechspace.com/docs/glossary.md#rest) requests instead. See [Core concepts](https://fluxerly.neontechspace.com/docs/core-concepts.md)
### Gateway gap
A gateway gap is a period when the connection may have missed events, such as while it recovers from a lost connection. A collector stops with an error after a gap, because replies may have been missed. A collector given a guild ID stops only when that community's shard recovers, and one without a guild ID stops when any shard does. See [Events and collectors](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#ask-a-question-without-missing-a-fast-reply)
### Guard
A guard is a check that runs before a command and can deny it with a reason. The exported `guards` include `guildOnly()`, `dmOnly()`, `ownerOnly()` and `requirePermissions(names)`. See [Commands](https://fluxerly.neontechspace.com/docs/commands.md#guard-limit-and-wrap-commands)
### Guild
A guild in the API is a community in Fluxer. The app says community, while API fields and SDK names such as `guildId` and `guilds.fetch` say guild. A community has its own [channels](https://fluxerly.neontechspace.com/docs/glossary.md#channel), [members](https://fluxerly.neontechspace.com/docs/glossary.md#member) and [roles](https://fluxerly.neontechspace.com/docs/glossary.md#role), and a bot is added to one through its installation link. See [Create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md) and [Communities and permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md)
## H
### Handler
A handler is a function that the SDK calls for each [event](https://fluxerly.neontechspace.com/docs/glossary.md#event) of one type. Register it with `client.on` or the `events` option of `runBot`. A handler that throws, or returns an Err, is reported and keeps receiving later events. See [Events and collectors](https://fluxerly.neontechspace.com/docs/events-and-collectors.md)
### Heartbeat
A heartbeat is a small message the SDK sends over the [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) connection at the interval Fluxer sets, to show the connection is still alive. When Fluxer does not acknowledge one before the next is due, the SDK treats the connection as lost and [reconnects](https://fluxerly.neontechspace.com/docs/glossary.md#reconnect). See [Troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md#the-connection-is-recovering)
## I
### ID
An ID is the unique number Fluxer gives each user, community, channel, message and role, and the SDK keeps every ID as a decimal string such as `"1234567890123456789"`. A string keeps the full value, because JavaScript numbers lose precision for values this large. A canonical ID has no sign, surrounding whitespace or leading zeroes. Methods trim surrounding whitespace from an ID before use, as Fluxer does, so `" 123 "` acts as `"123"`. An ID passed as a number fails before any request, because a JavaScript number holding a real Fluxer ID has already lost digits. See [snowflake](https://fluxerly.neontechspace.com/docs/glossary.md#snowflake)
### Identify
Identify is the gateway command that logs a [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard) in and starts a new [session](https://fluxerly.neontechspace.com/docs/glossary.md#session). Fluxer limits how often a bot may identify, so the SDK spaces the Identify commands of several shards. See [Sharding](https://fluxerly.neontechspace.com/docs/sharding.md)
### Intent
Fluxer has no gateway intents, so a bot receives events without turning any on, except presence updates for chosen members, which need `client.presence.setMembers`. To ask Fluxer not to send event types the bot does not use, set the client's `gateway.ignoredEvents` option. See [Configuration](https://fluxerly.neontechspace.com/docs/configuration.md)
## L
### Log level
A log level says how severe an SDK log record is, from Trace, Debug and Info through Warn and Error to Fatal. Trace and Debug are for detail that is off by default, Info for normal milestones such as readiness, Warn for problems the bot survives, such as a dropped event, and Error for failures, such as a failed handler. Fatal is the highest level, so a Fatal threshold hides failed handlers. See [Logging](https://fluxerly.neontechspace.com/docs/logging.md)
## M
### Member
A member is a user's membership in one [community](https://fluxerly.neontechspace.com/docs/glossary.md#guild), including the [roles](https://fluxerly.neontechspace.com/docs/glossary.md#role) the user holds there. The same user is a separate member in each community. See [Communities and permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md)
### MFA
MFA means multi-factor authentication. A community can require it for moderation actions, such as banning a member. Fluxer then refuses those actions from a bot unless the bot owns the community or the account that owns its application has MFA enabled. See [Communities that require two-factor authentication](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#communities-that-require-two-factor-authentication)
### Middleware
Middleware is a function that wraps every later handler or command and decides whether to continue by calling `next`. Add event middleware with `client.use`, and command middleware with the command router's `use` option. See [Commands](https://fluxerly.neontechspace.com/docs/commands.md#guard-limit-and-wrap-commands) and the [client reference](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#use)
## O
### OAuth
OAuth lets a person approve an application's access to their account through a consent page, after which the application exchanges the returned code for tokens. A client created with `oauth.create` builds the consent URL and makes the exchange. See [Webhooks and OAuth](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md)
## P
### Permission
A permission is one action a member may take in a [community](https://fluxerly.neontechspace.com/docs/glossary.md#guild) or one of its channels, such as sending messages or banning members. Each [role](https://fluxerly.neontechspace.com/docs/glossary.md#role) grants a set of permissions, and a channel's overwrites can allow or deny them there. Fluxer refuses a request that needs a permission the bot lacks. See [Communities and permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md)
### PKCE
PKCE is an OAuth safeguard: The application creates a secret verifier and sends only its hash when the consent flow starts, then proves it started the flow by sending the verifier when it exchanges the code. The `oauth.createPkce` helper creates the pair. See [Webhooks and OAuth](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md)
### Prefix command
A prefix command is a message that starts with a chosen prefix, such as `!ping` with prefix `!`. A [command router](https://fluxerly.neontechspace.com/docs/glossary.md#command-router) matches the name after the prefix and runs that command. See [Commands](https://fluxerly.neontechspace.com/docs/commands.md)
## R
### Rate limit
A rate limit caps how many requests Fluxer accepts in a period. Fluxer answers HTTP 429 when a limit is reached. The SDK then waits for the delay Fluxer names and sends the request again when its body can be reused, logging long waits. A request fails at once instead when that wait would pass its deadline. See [Troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md)
### Reconnect
The client reconnects by itself after it loses a [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) connection, and [resumes](https://fluxerly.neontechspace.com/docs/glossary.md#resume) the session when it can. Each lost connection logs a `lifecycle.connectionLost` record that names the next step. A failure the SDK does not retry, such as a rejected token, ends with a `lifecycle.connectionEnded` record instead. See [Troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md#the-connection-is-recovering)
### REST
REST is Fluxer's HTTP API for reading and changing resources, such as sending a message or fetching a community. REST requests work without the [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) connection. HTTP 204 is a successful response without a value. For a route without an SDK method, use `client.rest.request` with a path after `/v1`. See [Raw requests and events](https://fluxerly.neontechspace.com/docs/raw-requests-and-events.md) and the [client reference](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#rest)
### Result
A Result holds either a success or an expected failure. Check `isErr()`: If it is true, read `error`, otherwise read `value`. The `orThrow` function returns the value or throws the error. See [Reliability](https://fluxerly.neontechspace.com/docs/reliability.md)
### ResultAsync
A ResultAsync is a Result that is still being computed. Default API requests return one, start when called and give a [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) when awaited. See [Reliability](https://fluxerly.neontechspace.com/docs/reliability.md)
### Resume
A resume continues an existing [session](https://fluxerly.neontechspace.com/docs/glossary.md#session) after a lost connection, and Fluxer then replays most events the bot missed. Member lists, member chunks and thread lists are not replayed. When a session cannot be resumed, the SDK starts a new one with [Identify](https://fluxerly.neontechspace.com/docs/glossary.md#identify). See [Reliability](https://fluxerly.neontechspace.com/docs/reliability.md)
### Role
A role is a named set of permissions in a [community](https://fluxerly.neontechspace.com/docs/glossary.md#guild). A member can hold several roles, and their permissions combine. See [Communities and permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md)
### Role hierarchy
The role hierarchy is the ordering of a community's roles. It limits which members and roles a bot can manage. The `hierarchy` helpers compare roles and members that the bot already has, and `members.fetchCanManage` fetches the data for a member hierarchy check, using the bot or a moderator given as `actorUserId`. See [Communities and permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md)
## S
### Session
A session is one gateway login of a [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard). It starts with [Identify](https://fluxerly.neontechspace.com/docs/glossary.md#identify) and continues with a [resume](https://fluxerly.neontechspace.com/docs/glossary.md#resume) after a short connection loss. See [Sharding](https://fluxerly.neontechspace.com/docs/sharding.md)
### Shard
A shard is one gateway connection that carries events for part of a bot's communities. Most bots need only one. Setting `sharding: "auto"` picks the number of shards when the bot connects. See [Sharding](https://fluxerly.neontechspace.com/docs/sharding.md)
### Snowflake
A snowflake is the format of Fluxer [IDs](https://fluxerly.neontechspace.com/docs/glossary.md#id): A 64-bit number that also records when the object was created. The `snowflakes` helper reads the creation time from an ID. See the [snowflakes reference](https://fluxerly.neontechspace.com/docs/api/js-ts/builders-and-formatting/#snowflakes)
### Subscription
A subscription delivers one event type to one [handler](https://fluxerly.neontechspace.com/docs/glossary.md#handler) through its own queue. The `client.on` method returns one, and `runBot` creates one per handler. Its `close()` method stops the delivery, and `waitForClose()` waits until it has stopped. See [Events and collectors](https://fluxerly.neontechspace.com/docs/events-and-collectors.md)
### Supervisor
A supervisor runs a bot's shards in several child Node.js processes. A supervisor created with `supervisor.create` starts each child with its shard assignment, watches its state, restarts it after a crash and shuts every child down together. See [Sharding](https://fluxerly.neontechspace.com/docs/sharding.md)
## T
### Test client
A test client is a real client connected to an in-memory Fluxer instead of the network. The `createTestClient` and `createTestBot` functions create one, and a test uses it to deliver events and check the requests the bot sent. See [Testing](https://fluxerly.neontechspace.com/docs/testing.md)
### Token
A token is a secret that proves who a request comes from. The bot token runs the bot and belongs in an environment variable such as `FLUXER_BOT_TOKEN`, never in the code. A webhook has its own token, and OAuth gives an application tokens that act for one user. See [Create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md) and [Webhooks and OAuth](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md)
## U
### Uncertain write
An uncertain write is a request that may have succeeded even though the SDK did not receive a clear result, for example when the connection dropped after sending. Check the current state on Fluxer before repeating it, or the action can happen twice. See [Reliability](https://fluxerly.neontechspace.com/docs/reliability.md)
## W
### Webhook
An incoming webhook has a URL with its own token that posts messages to one channel, without a bot account or gateway connection. Use `createWebhookClient` to send through it. See [Webhooks and OAuth](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md)
---
# Read communities and plan permission-aware work
Read communities, members and channels, calculate permissions, grant roles and moderate members deliberately
A [community](https://fluxerly.neontechspace.com/docs/glossary.md#guild), called a guild in the API, has its own [members](https://fluxerly.neontechspace.com/docs/glossary.md#member), [roles](https://fluxerly.neontechspace.com/docs/glossary.md#role) and channels. Each kind of community data comes from its own request: Fetching a community does not load its members or roles. Fetch the data a decision needs, then let Fluxer check the final request, because a permission calculated locally does not authorize anything by itself
## Read a community and one member together
Fetch the community and one member to show their details. Add this helper to a module that already has a bot [`Client`](https://fluxerly.neontechspace.com/docs/api/js-ts/client/)
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function readGuildMember(client: Client, guildId: string, userId: string) {
const [guild, member] = await Promise.all([
client.guilds.fetch(guildId),
client.members.fetch({ guildId, userId }),
])
if (guild.isErr()) return guild
if (member.isErr()) return member
return { guild: guild.value, member: member.value }
}
```
The helper returns the community and the member, or the first failed [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) if either request fails. The returned objects are [frozen snapshots](https://fluxerly.neontechspace.com/docs/glossary.md#frozen-snapshot) that do not change afterward
A member's [`user`](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#guildmember-user) holds the account's display name and avatar, which can differ from its nickname and avatar in this community. A community's [`badgeIds`](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#guild-badgeids) name its custom badges, and [`instance.fetchBadges`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#instance-fetchbadges) reads their names and images. The community also has `rulesChannelId`, `vanityUrlCode` and `nsfwLevel`
The bot must be a member of the community for [`Guilds.fetch`](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#guilds-fetch) to succeed, and the result does not include the member list. The two reads are separate observations, so neither proves that a later role action will still be allowed
The `guildHealthUpdate` event reports lag and recovery of a community's server through `guildId` and `degraded`. A degraded server is lagging, not disconnected or unavailable. The notice does not reconnect the client or invalidate community caches
## List channels by type
Each channel has a `type`. Comparing it with a `ChannelType` constant tells TypeScript which fields that channel has, such as `topic` for text channels or `bitrate` for voice channels
```ts
import { ChannelType, type Client, type GuildChannel } from "@neontechspace/fluxerly"
function describeChannel(channel: GuildChannel): string {
const name = channel.name ?? channel.id
switch (channel.type) {
case ChannelType.Text:
return `#${name}: ${channel.topic ?? "no topic"}`
case ChannelType.Announcement:
return `#${name}: announcements, ${channel.topic ?? "no topic"}`
case ChannelType.Voice:
return `${name}: voice at ${channel.bitrate ?? "unknown"} bps`
case ChannelType.Category:
return `${name}: category`
case ChannelType.Link:
return `${name}: link to ${channel.url ?? "an unknown address"}`
case ChannelType.Forum:
case ChannelType.Media:
return `${name}: posts with ${channel.availableTags?.length ?? 0} tags`
case ChannelType.AnnouncementThread:
case ChannelType.PublicThread:
case ChannelType.PrivateThread:
return `${name}: thread in ${channel.parentId}`
case "unknown":
console.warn(`Channel ${channel.id} has type ${channel.rawType}, which this SDK version does not know`)
return `${name}: unsupported type ${channel.rawType}`
}
}
export async function listChannels(client: Client, guildId: string) {
const channels = await client.channels.fetchAll(guildId)
return channels.map((list) => list.map(describeChannel))
}
```
The helper returns a Result with one line for each channel the bot can see. A channel type that Fluxer adds later, which this SDK version does not know yet, arrives with `type` set to `"unknown"` and the number Fluxer sent in `rawType`. Handling the `"unknown"` case makes the `switch` complete, so TypeScript can check that every case returns a value
Announcement channels have the same topic and message fields as text channels. See [announcement channels](https://fluxerly.neontechspace.com/docs/announcement-channels.md) to create or convert one, publish a message and follow it from a text channel in the same community or another one
Threads, forum channels and media channels have their own types as well. See [threads](https://fluxerly.neontechspace.com/docs/threads.md) and [forum channels](https://fluxerly.neontechspace.com/docs/forum-channels.md) for their fields
## Reorder channels and check the result
A reorder sends a list of moves that Fluxer applies one after another. If a later move fails, the earlier moves stay applied, and the error does not list which ones finished. Keep the failure, then read the channels to see their actual parents and positions before sending any move again
```ts
import { describeError, type ChannelPosition, type Client } from "@neontechspace/fluxerly"
export async function reorderChannels(client: Client, guildId: string, positions: readonly ChannelPosition[]) {
const reordered = await client.channels.reorder(guildId, positions)
if (reordered.isOk()) return reordered
const actual = await client.channels.fetchAll(guildId)
if (actual.isErr()) {
console.error("Could not read the channels after a failed reorder:", describeError(actual.error))
} else {
const layout = actual.value.map(({ id, parentId, position }) => ({ id, parentId, position }))
console.warn("Reorder failed, channels now:", JSON.stringify(layout))
}
return reordered
}
```
The helper returns the failed Result from `channels.reorder` unchanged and logs the layout that `channels.fetchAll` returns. A failed read is logged as well, and says nothing about whether the moves applied. The list holds the channels the bot can see, without threads. Compare it with the intended layout and send only the moves that are still missing
With the native Effect API, `Effect.tapError` runs the read while the reorder failure stays in the error channel. The read's own failure is caught, so it cannot replace the reorder failure:
```ts
import { Effect } from "effect"
import type { ChannelPosition, Client } from "@neontechspace/fluxerly/effect"
export function reorderChannelsWithEffect(client: Client, guildId: string, positions: readonly ChannelPosition[]) {
return client.channels.reorder(guildId, positions).pipe(
Effect.tapError(() =>
client.channels.fetchAll(guildId).pipe(
Effect.flatMap(channels => {
const layout = channels.map(({ id, parentId, position }) => ({ id, parentId, position }))
return Effect.logWarning("Reorder failed, channels now", JSON.stringify(layout))
}),
Effect.catch(error => Effect.logError("Could not read the channels after a failed reorder", error)),
),
),
)
}
```
## Read the member verification level
The community's `verificationLevel` describes its member verification policy. The `GuildVerificationLevels` constants range from `None` through `High`. Fluxer retired its phone-verification level, so there is no `VeryHigh` constant. This policy is separate from the [two-factor requirement for moderation](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#communities-that-require-two-factor-authentication)
## Check permissions using available data
Check whether a member has the `ManageRoles` permission from data the application already holds. Supply a [`PermissionInput`](https://fluxerly.neontechspace.com/docs/api/js-ts/roles-and-permissions/#permissioninput) with the community, the member, every role in `member.roleIds`, the implicit everyone role whose ID equals `guild.id` and, optionally, the target channel
```ts
import { Permissions, type Client, type PermissionInput } from "@neontechspace/fluxerly"
export function hasManageRoles(client: Client, input: PermissionInput) {
const calculated = client.permissions.calculate(input)
return (calculated & Permissions.ManageRoles) === Permissions.ManageRoles
}
```
The helper returns `true` or `false` from the supplied data. It throws `GuildOperationError` with reason `input` if that data is inconsistent or incomplete
A thread has no permission overwrites of its own, because Fluxer calculates its permissions in its parent channel. To check a thread, supply the thread as `channel` and its parent channel as `parentChannel`. The calculation then uses the parent's overwrites and grants `SendMessages` exactly when `SendMessagesInThreads` is granted, as Fluxer does. A thread without its parent, or with another channel as `parentChannel`, fails with reason `input`. The [`permissions.fetch`](https://fluxerly.neontechspace.com/docs/api/js-ts/roles-and-permissions/#permissionhelpers-fetch) method reads the parent itself when its `channelId` names a thread
To reuse cached data, call `client.permissions.fetch(target, { preferCache: true })`. It takes each part from an enabled cache and fetches only what is missing, which is how `guards.requirePermissions` decides. Cached parts follow the gateway events applied so far and can come from different moments, so keep the default fresh read for the moment right before an action where a stale grant matters
To see what the bot can do in every channel, call [`permissions.fetchChannels`](https://fluxerly.neontechspace.com/docs/api/js-ts/roles-and-permissions/#permissionhelpers-fetchchannels) with the bot's own ID. It reads the community once and calculates each channel locally, instead of reading again for every channel
```ts
import { ChannelType, permissionBits, type Client } from "@neontechspace/fluxerly"
export async function channelsWhereBotCanSend(client: Client, guildId: string) {
const botId = client.users.getSelf()?.id
if (botId === undefined) return []
const result = await client.permissions.fetchChannels({ guildId, userId: botId })
if (result.isErr()) throw result.error
return result.value
.filter(
({ channel, permissions }) =>
(channel.type === ChannelType.Text ||
channel.type === ChannelType.Voice ||
channel.type === ChannelType.Announcement) &&
permissionBits.hasAll(permissions, ["ViewChannel", "SendMessages"]),
)
.map(({ channel }) => channel.id)
}
```
These channel types accept ordinary messages, and their current permission bits allow sending. Forum and media channels need a new post instead. Fluxer still checks the final request
A timeout is how a bot mutes a member for a set time. A timed-out member keeps their permission bits, while Fluxer blocks sending messages, editing and publishing their own messages, reacting, uploading, typing, changing their own nickname, writing in threads and joining voice. The `client.members.timeoutState(member)` method returns `"active"`, `"none"` or `"unknown"`
A member without the `communicationDisabledUntil` field is `"unknown"`, and `members.fetch` always includes it. To show a permission to people, `permissionBits.label("ManageGuild")` gives Fluxer's own name for it, "Manage community". These are community-scope titles, and a channel's permission screen calls `ManageChannels` "Manage channel" and `ManageRoles` "Manage permissions"
What does a calculated permission not cover?
The [`permissions.calculate`](https://fluxerly.neontechspace.com/docs/api/js-ts/roles-and-permissions/#permissionhelpers-calculate) method makes no request and reads no cache. Its result does not establish channel visibility, role hierarchy, multi-factor authentication requirements, application authorization or Fluxer's final decision
In a thread, the result also does not show whether the member can see a private thread, which Fluxer allows only to its members and to members who can manage threads, or whether the thread is archived or locked. For prefix commands, the `guards.requirePermissions` guard in the [commands guide](https://fluxerly.neontechspace.com/docs/commands.md) checks the same permission bits from cached or fetched data. Private-thread membership and archived or locked state need separate checks
## Change part of a channel overwrite
The `channels.setPermissionOverwrite` method replaces both bit sets of an overwrite. The `permissionBits.patchOverwrite` helper changes only the named permissions and keeps every other bit
```ts
import { permissionBits, type Client, type PermissionOverwrite } from "@neontechspace/fluxerly"
export async function quietRole(client: Client, channelId: string, roleId: string, current?: PermissionOverwrite) {
const { allow, deny } = permissionBits.patchOverwrite(current, {
deny: ["SendMessages", "AddReactions"],
inherit: ["ViewChannel"],
})
return await client.channels.setPermissionOverwrite(channelId, { id: roleId, type: "role", allow, deny })
}
```
Pass the overwrite as read from the channel, or `undefined` when there is none. In the change, `allow` also stops denying, `deny` also stops allowing and `inherit` clears both. A permission in more than one list throws `HelperError`. A result with `allow` and `deny` both `0n` has no effect, so remove such an overwrite with `channels.removePermissionOverwrite`
## Check what Fluxer will refuse in an overwrite
Unless the bot has `Administrator`, an overwrite change can allow, or stop denying, only permissions the bot has in the channel. Fluxer refuses anything more with `missingPermissions`. The [`permissionBits.refusedGrants`](https://fluxerly.neontechspace.com/docs/api/js-ts/roles-and-permissions/#permissionbits) helper returns the bits Fluxer would refuse, so the application can check a change before sending it. The [`channels`](https://fluxerly.neontechspace.com/docs/api/js-ts/channels/#channels-setpermissionoverwrite) reference describes how each method applies the rule
```ts
import { permissionBits, type Client, type PermissionOverwrite } from "@neontechspace/fluxerly"
export async function allowTtsIfPossible(
client: Client,
guildId: string,
channelId: string,
roleId: string,
current: PermissionOverwrite | undefined,
) {
const botId = client.users.getSelf()?.id
if (botId === undefined) return
const held = await client.permissions.fetch({ guildId, userId: botId, channelId })
if (held.isErr()) return held
const { allow, deny } = permissionBits.patchOverwrite(current, { allow: ["SendTtsMessages"] })
if (permissionBits.refusedGrants(current, { allow, deny }, held.value) !== 0n) return
return await client.channels.setPermissionOverwrite(channelId, { id: roleId, type: "role", allow, deny })
}
```
## Find the channels a category change will rewrite
When a category's overwrites change, Fluxer copies the new overwrites to every child whose overwrites equal the category's old ones, with no way to opt out. The `permissionBits.sameOverwrites(first, second)` helper compares two lists as Fluxer does, so the application can find those children before the change
```ts
import { permissionBits, type GuildChannel } from "@neontechspace/fluxerly"
export function syncedChildren(category: GuildChannel, channels: readonly GuildChannel[]) {
const overwrites = category.permissionOverwrites
// Unknown until the category is read with its overwrites, such as through channels.fetch
if (overwrites === undefined) return undefined
return channels.filter(
({ parentId, permissionOverwrites }) =>
parentId === category.id &&
permissionOverwrites !== undefined &&
permissionBits.sameOverwrites(permissionOverwrites, overwrites),
)
}
```
## Grant a configured opt-in role
Call this helper from a command in a community that lets a member opt into a role. Take `roleId` from trusted application configuration, not from command text, and configure only roles that members may assign to themselves. Fluxer checks the [role hierarchy](https://fluxerly.neontechspace.com/docs/glossary.md#role-hierarchy) on the request: The bot's highest role must rank above the role, whichever member receives it
```ts
import type { Client, Message } from "@neontechspace/fluxerly"
export async function grantOptInRole(
client: Client,
message: Message,
roleId: string,
) {
if (message.author.isBot || !message.guildId) return
return await client.members.addRole({ guildId: message.guildId, userId: message.author.id }, roleId)
}
```
The helper gives the configured role to the command's author. It returns `undefined` when the message is not from a person in a community, and otherwise the Result of the role request. Fluxer enforces the role hierarchy, management restrictions and the bot's `ManageRoles` permission on [`addRole`](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#members-addrole), so the command must inspect that Result and apply any additional access policy of the application
## Give a role an icon
A role shows an image or a single Unicode emoji, never both. Setting one replaces the other, and null removes it
```ts
import { assets, orThrow, type Client, type RoleReference } from "@neontechspace/fluxerly"
export async function setRoleEmoji(client: Client, role: RoleReference) {
return orThrow(await client.roles.edit(role, { unicodeEmoji: "🛡️" }))
}
export async function setRoleImage(client: Client, role: RoleReference, png: Buffer) {
const updated = orThrow(await client.roles.edit(role, { icon: `data:image/png;base64,${png.toString("base64")}` }))
return assets.roleIcon(updated)
}
```
Fluxer accepts a still image of at most 256 KiB and from 32 through 1024 pixels on each side. The bot needs `ManageRoles`, and its highest role must rank above the role
## Moderate members
Moderation actions follow the same pattern as roles. A moderation command should also check the moderator who typed it, so a member cannot use the bot against someone who ranks above them. The `actorUserId` option of `fetchCanManage` checks that person instead of the bot. This helper bans a member for one day and deletes their messages from the last hour
```ts
import type { Client, MemberReference } from "@neontechspace/fluxerly"
export async function banForOneDay(client: Client, target: MemberReference, moderatorId: string) {
const [bot, moderator] = await Promise.all([
client.members.fetchCanManage(target),
client.members.fetchCanManage(target, { actorUserId: moderatorId }),
])
if (bot.isErr()) return bot
if (moderator.isErr()) return moderator
if (!bot.value || !moderator.value) return
return await client.members.ban(target, {
durationMs: 24 * 60 * 60 * 1000,
deleteMessagesMs: 60 * 60 * 1000,
})
}
```
The helper returns `undefined` when the bot or the moderator does not rank above the target, and otherwise the Result of a rank check or the ban. Omit `durationMs` for a permanent ban. Both durations are in milliseconds and must be whole seconds. Fluxer checks the bot's permissions, such as Ban Members, and the role hierarchy for each request
The SDK checks ban options before sending anything. An invalid option fails with a `GuildOperationError` whose `reason` is `input`, and its `inputValidation.path` names the field, such as `input.durationMs`. A [`duration` command argument](https://fluxerly.neontechspace.com/docs/commands.md#convert-arguments-before-execution) can be passed to `durationMs` unchanged when it sets `wholeSeconds: true`, `min: 60_000` and `max: 63_072_000_000`
The [`members.kick`](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#members-kick) and `members.timeout` methods take the same member reference. A timeout mutes a member in chat for a set time, while `members.setMute` only mutes a member who is connected to voice. Use `members.unban` and `members.fetchBans` to review and lift bans. In a prefix command, `guards.requirePermissions(["BanMembers"])` makes sure the person who typed the command also has that permission
Compare ranks from data already held
The `fetchCanManage` method fetches fresh community, member and role data for each check. When the application already holds that data, the `hierarchy` helpers compare it without a request: `hierarchy.canManage({ guild, actor, target, roles })` checks one member against another, and `hierarchy.compare` and `hierarchy.isAbove` order two roles. Like `fetchCanManage`, they check rank only, not permissions
For roles, `hierarchy.highestRole(member, roles)` returns a member's highest explicit role, and `hierarchy.canManageRole({ guild, actor, role, roles })` checks whether the actor outranks a role. Administrator does not bypass rank, so also check the `ManageRoles` permission for the permission half
The caches can supply that data. With `cache.roles` enabled, `roles.getAll(guildId)` returns a community's roles once the cache knows the list is complete, such as after its `guildCreate` or a `roles.fetchAll` while connected, and `undefined` otherwise. With `cache.members` enabled, `members.getSelf(guildId)` returns the bot's own member, which each `guildCreate` and `members.fetchSelf` stores
The member that Fluxer attaches to message, reaction and typing events refreshes the cache for any member who speaks, reacts or types, whichever `messageFields` the client selects, while a voice state's member is never stored because it can lag behind role edits
## Communities that require two-factor authentication
A community owner can require two-factor authentication ([MFA](https://fluxerly.neontechspace.com/docs/glossary.md#mfa)) for moderation. In such a community, only the owner and accounts with two-factor authentication enabled can use `Administrator`, `BanMembers`, `KickMembers`, `ManageChannels`, `ManageGuild`, `ManageMessages`, `ManageRoles`, `ManageThreads`, `ManageWebhooks` and `ModerateMembers`. That covers kicks, bans, timeouts, role changes, deleting other people's messages, moderating threads and changes to channels, webhooks and community settings
A bot cannot enable two-factor authentication itself. Its account follows the account that owns its application, so the bot can act in these communities only when that owner account has two-factor authentication enabled, or when the bot owns the community
Otherwise Fluxer refuses the request with HTTP 400 after confirming that the bot holds the permission. To tell this failure apart from other rejections, check `errors.apiCode(result.error) === "twoFactorRequired"`. The `errors.apiCode` function, imported with `errors` from the SDK, returns the name of Fluxer's error code, or `undefined` when the error carries no code that the SDK recognizes
Repeating the request fails the same way until the application owner enables two-factor authentication. A calculated permission from `permissions.calculate` or a passing `guards.requirePermissions` guard does not rule this out, because both read role permissions and not the community's requirement
To check a community in advance, read the [`mfaLevel`](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#guild-mfalevel) of the community from `guilds.fetch` or a `guildCreate` event. The value `GuildMfaLevels.Elevated` means the community has this requirement, and `GuildMfaLevels.None` means it does not. The SDK cannot see whether the application owner has two-factor authentication enabled, so an elevated level means a moderation request can fail, not that it will. Fluxer's API reference describes [MFA levels](https://docs.fluxer.com/http-api/guilds/#mfa-levels) and [elevated permissions](https://docs.fluxer.com/http-api/permissions/#elevated-permissions)
## Read audit records
Use `auditLogs.fetchPage` or the bounded `auditLogs.iterate` scan with `ViewAuditLog` permission. Recorded message-deletion durations are exposed in `options.deleteMessagesMs`, rounded to whole milliseconds. A duration that would overflow the safe integer range fails the REST page rather than returning partial entries. The same invalid duration in a gateway audit event follows the configured malformed-dispatch policy. Pass `userId`, `actionType` or both. An unfiltered Fluxer read can merge message-deletion records, so the SDK requires a filter
## Voice controls versus a voice connection
Fluxerly handles gateway voice signaling cleanly today through `client.voice` (`join`, `leave`, `updateState`) together with typed `voiceStateUpdate`, `voiceServerUpdate`, `voiceSignal` and opcode 12 `gatewayError` refusal events, all while keeping `gateway.ignoredEvents: "auto"` active. Member voice controls (`members.move`, `members.disconnect`, `members.setMute`, `members.setDeaf`) also work subject to Fluxer's permissions
A voice state, whether from `voiceStateUpdate`, a `voiceStateSnapshot` or a private call, also reports `isE2eeCapable` for a client that supports encrypted call media, `isPeerToPeer` for a connection that does not pass through LiveKit, and `version`, Fluxer's counter for that participant's state. An omitted flag reads as `false`. Fluxer's server issues the key for that encryption, so it is not end-to-end encryption
Built-in audio transport and playback are planned for Fluxer's own upcoming voice engine so bots avoid lock-in to a temporary media layer. Bots needing audio today can pass the typed `voiceServerUpdate` grant straight to their own media client, while Fluxerly keeps signaling, shard routing and refusal handling typed and engine-agnostic. A `Connect` or `Speak` permission describes what Fluxer allows, and the bot's gateway `connect()` opens the gateway session rather than a media stream. See [voice signaling](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#voice) and [member voice controls](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#members-move) for the current operations
## Wire it up
In a `runBot` bot, the command context provides the `client` and the incoming message. This bot answers `!notify` by granting the role configured in `OPT_IN_ROLE_ID`
```ts
import { guards, runBot } from "@neontechspace/fluxerly"
const optInRoleId = process.env.OPT_IN_ROLE_ID
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
notify: {
description: "Join the announcements role",
guard: guards.guildOnly(),
execute: async ({ client, message, reply }) => {
if (!optInRoleId || !message.guildId) return reply("The opt-in role is not configured")
const member = { guildId: message.guildId, userId: message.author.id }
const added = await client.members.addRole(member, optInRoleId)
return added.isErr() ? added : reply("Role added")
},
},
},
},
})
```
Returning a failed Result from `execute` reports it with the command name, without stopping the bot. In a direct message, `guards.guildOnly()` denies `!notify`, and the router explains why, as `runBot` answers rejected commands by default
---
# Read history and use the message cache
Read recent messages with fetchHistory and iterateHistory, search the index and use locally cached copies
After the [first reply bot](https://fluxerly.neontechspace.com/docs/quick-start.md) works, read earlier messages from a channel, search them or keep recent ones in a local [cache](https://fluxerly.neontechspace.com/docs/glossary.md#cache). Reading history is a request to Fluxer and does not need the [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) connection
## Scan for one message
Find the first recent message that matches a rule. Add this helper to a module that already has a bot [`Client`](https://fluxerly.neontechspace.com/docs/api/js-ts/client/)
```ts
import type { Client, Message } from "@neontechspace/fluxerly"
export async function findRecentMessage(
client: Client,
channelId: string,
matches: (message: Message) => boolean,
) {
for await (const item of client.messages.iterateHistory(channelId, { maxItems: 200 })) {
if (item.isErr()) return item
if (matches(item.value)) return item
}
return undefined
}
```
The helper returns a [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) with the matching message or the failure that stopped the read. It returns `undefined` if none of the 200 newest messages match
The [`iterateHistory`](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-iteratehistory) method reads newest first and requests the next page only when the loop needs it, so stopping early saves requests. The required `maxItems` bounds the scan, so older messages can remain unread. To read a single page of up to 100 messages instead, use [`fetchHistory`](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-fetchhistory), as the [last section](https://fluxerly.neontechspace.com/docs/history-and-cache.md#wire-it-up) shows
## Read pinned messages
Use `messages.fetchPins` for one page or `messages.iteratePins` with `maxItems` for a bounded scan. Pins are ordered by pin time, not message creation time. Page ordering and cursor progress compare every fractional timestamp digit and normalize timezone offsets, so distinct pins less than a millisecond apart can advance the scan. Equal instants remain equal and can stall a multi-page scan. Preserve `nextBefore` unchanged in a manual loop and skip duplicate message IDs
## Search the message index
When the text to look for is known, ask Fluxer's search index for one page of results. The index can lag behind the newest messages
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function searchChannel(client: Client, channelId: string, text: string) {
const result = await client.messages.search({ channelId }, { content: text, limit: 10 })
if (result.isErr()) return result
if (result.value.indexing) return undefined
return result.value.messages
}
```
The helper returns the matching messages, a failed Result, or `undefined` while Fluxer is still preparing its search index. It does not wait for the index or add results to the cache. To read the next page, increase `page` and keep `limit` unchanged
Search pages also include channel snapshots. An unnamed group DM has `name: null`, while another private channel may omit the name. The `includeNsfw` filter requests age-restricted channel results. In an age-restricted community, guild search includes those results for eligible callers, including bots, even when the filter is omitted or false. Channel access checks still apply
To search several pages, use [`iterateSearch`](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-iteratesearch) with `maxItems` as the limit. Results can shift while the index changes during the scan
## Limit the message cache
The message cache keeps recent messages in memory so they can be read without a request. It is off until configured. Create a client with a token supplied by the application
```ts
import { createClient } from "@neontechspace/fluxerly"
export function createCachedClient(token: string) {
return createClient({
token,
cache: {
messages: {
maxEntries: 500,
maxBytes: 2_000_000,
maxAgeMs: 60_000,
},
},
})
}
```
This client keeps up to 500 messages from sends, reads, history pages and gateway events, within about two megabytes and for at most one minute each. Without these settings, an enabled message cache keeps up to 1,000 messages in 8 MiB with no age limit. The same `cache` option works in `runBot`
A function as `maxAgeMs` chooses the age limit per message, such as `maxAgeMs: (message) => (message.author.isBot ? 0 : 60_000)` to keep only messages from people. Zero skips keeping a message, and `null` keeps it without an age limit. Every cache category accepts the same kind of function
To release cached data while the bot runs, call `client.cache.clear("messages")`, or `client.cache.clear()` for every category. The `client.cache.delete(kind, key)` method removes one entry, with keys such as `channelId:messageId` for messages. Neither changes anything on Fluxer
Why can a message be missing from the cache?
The cache stores data only in memory. A message may be missing because it was removed to make room, expired or conflicted with another observation of the same message. A lost gateway connection also clears the messages cached before it, even when the connection recovers, because changes during the gap may have been missed. The entry and byte limits do not count runtime overhead or copies held elsewhere in the application
To react to cache changes, register a listener with `client.cache.onChange`, which reports each stored, deleted or cleared entry. A listener that returns a promise has at most 256 unfinished calls, and up to 256 more changes wait for them
Beyond that, the oldest waiting change is dropped and logged as `cache.changesDropped`. Shutdown does not wait for unfinished calls, so changes still waiting then are dropped and logged the same way. Pass `{ concurrency, maxPendingChanges }` as the second argument to change these limits
Deleting a channel or a [thread](https://fluxerly.neontechspace.com/docs/threads.md) removes its cached messages. Deleting a text, announcement, forum or media channel also deletes its threads, and Fluxer sends no thread deletion for them. A message does not record which channel holds its thread, so the cache then also removes the messages of every channel in that community that the channel cache does not hold
Messages read through REST carry no community, so they count as possibly in that community. Without `cache.channels`, all of these messages go. With it, which also fills from each community's startup snapshot, messages in the channels and threads it still holds stay
See [`ClientOptions.cache`](https://fluxerly.neontechspace.com/docs/api/js-ts/options/#clientoptions-cache) and [`MessageCacheSettings`](https://fluxerly.neontechspace.com/docs/api/js-ts/caching/#messagecachesettings) for the complete cache contract
## Use the cache, then fetch if needed
Use a cached message when a recent copy is good enough, and fetch it from Fluxer otherwise. Pass a `MessageReference` with both `channelId` and `id`
The received `message.messageReference` is a different type, `MessageContextReference`, whose `id` is optional. Check `id` before building the `MessageReference`. An [announcement-channel follow notice](https://fluxerly.neontechspace.com/docs/announcement-channels.md#find-where-a-copy-came-from) identifies only a source channel, not a message to fetch
```ts
import { orThrow, type Client, type MessageReference } from "@neontechspace/fluxerly"
export async function readCachedOrFetch(client: Client, message: MessageReference) {
const cached = client.messages.get(message)
if (cached !== undefined) return cached
return orThrow(await client.messages.fetch(message, { timeoutMs: 5_000 }))
}
```
A cached copy returns immediately without a request. Otherwise the helper [fetches](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-fetch) the message with a five-second deadline, and `orThrow` throws if that fails
The [`get`](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-get) method returns `undefined` when the client has no usable copy. A cached copy is a [frozen snapshot](https://fluxerly.neontechspace.com/docs/glossary.md#frozen-snapshot) of the message as it was when observed, so use `fetch` when the task needs its current state
A cached channel's `lastMessageId` is kept from when the channel was observed. Sending messages or creating posts does not update it, so fetch the channel with `client.channels.fetch` for a current value
## Check whether the limits fit
Each category in `client.diagnostics().caches` keeps running totals since the client was created. The `hits` and `misses` values count lookups such as `client.messages.get`, including lookups the SDK makes itself. The `evictions` value counts entries the cache removed on its own, with `capacity` for room within `maxEntries` or `maxBytes` and `expiry` for entries older than `maxAgeMs`
```ts
import type { Client } from "@neontechspace/fluxerly"
export function messageCacheReport(client: Client) {
const { hits, misses, evictions } = client.diagnostics().caches.messages
const lookups = hits + misses
return {
hitRate: lookups === 0 ? null : hits / lookups,
removedForRoom: evictions.capacity,
expired: evictions.expiry,
}
}
```
Frequent misses together with many capacity evictions suggest the limits are too small for the messages the bot reads again. Frequent misses with few evictions usually mean the bot looks up messages it never kept or that a lost connection cleared, so larger limits rarely help. Counting costs one increment per lookup or eviction, so the totals are always on. A disabled category reports zero
## Wire it up
In a `runBot` bot, cache settings sit beside the token, and commands read history through the `client` in their context. This bot answers `!recent` with the people who spoke in the channel's 20 newest messages
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
cache: { messages: { maxEntries: 500, maxAgeMs: 600_000 } },
commands: {
prefix: "!",
commands: {
recent: {
description: "List recent speakers",
execute: async ({ client, message, reply, signal }) => {
const page = await client.messages.fetchHistory(message.channelId, { limit: 20 }, { signal })
if (page.isErr()) return page
const people = page.value.filter((item) => !item.author.isBot)
const names = new Set(people.map((item) => item.author.username))
return reply(`Recent speakers: ${[...names].join(", ") || "none"}`)
},
},
},
},
})
```
Passing the command's `signal` stops the read when the bot shuts down. A failed read is returned from `execute`, so the router reports it with the command name. With the cache enabled, the page read can also store those messages for later `client.messages.get` lookups
---
# See what a bot is doing
Read the default log output, adjust levels and categories, and send records to an existing logger
Every client prints what it is doing by default: Startup, each [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard) (gateway connection) becoming ready, lost connections with their close code and next step, long rate-limit waits, shutdown, and every application error with its name, string `code`, message, stack, cause chain up to four levels and the first ten errors of an `AggregateError`. Other properties of an error, such as a `status` or a request ID, are not printed. The original error stays unchanged on `FailureReport.error` for an `onError` hook. Adjust the level for the whole client or one area, turn on Debug records while investigating, or send records to an existing logger. Records mask the bot token, the credential forms Fluxer uses and common credential names, such as Authorization headers, client secrets, passwords and cookies. A secret of another service that a bot logs itself may not be recognized, so keep such secrets out of error messages
## Read the default output
On a terminal the client prints one readable line per record: Time, level icon and name, category, the record's code in brackets, a message and its facts. Warnings and errors go to standard error, everything else to standard output. Success milestones such as `lifecycle.ready`, `lifecycle.connected`, `lifecycle.sessionRestored`, `lifecycle.drained` and `lifecycle.shutdownComplete` show `✓`, other Info records show `ℹ`, warnings show `▲` and errors show `✖`. A two-shard bot that starts, loses one connection and stops prints lines like these
```text
2026-09-27 03:14:20.850 ℹ INFO lifecycle [lifecycle.starting] Starting Fluxerly for fluxer.com with 2 shards version= instance=fluxer.com shards=2 totalShards=2
2026-09-27 03:14:20.853 ℹ INFO lifecycle [lifecycle.startupDeadline] Startup of 2 shards may take up to 31.0 s: The configured 30.0 s (connection.startupTimeoutMs) plus 1 s per additional shard, because the SDK starts shard sessions 1 s apart. Sending Identify adds up to 25 s while Fluxer starts the session startupTimeoutMs=31000 configuredMs=30000 shards=2 identifyWaitMs=25000
2026-09-27 03:14:20.891 ✓ INFO lifecycle [lifecycle.ready] Shard 0 is ready shardId=0 attempt=1 durationMs=36 mode=identify shards=2
2026-09-27 03:14:21.890 ✓ INFO lifecycle [lifecycle.ready] Shard 1 is ready shardId=1 attempt=1 durationMs=1033 mode=identify shards=2
2026-09-27 03:14:21.891 ✓ INFO lifecycle [lifecycle.connected] Connected to Fluxer as MyBot in 1520 communities communities=1520 shards=2
2026-09-27 03:14:22.233 ▲ WARN lifecycle [lifecycle.connectionLost] Shard 1 lost its connection. Close code 4000 (UNKNOWN_ERROR): The gateway reported an unspecified error. Reconnecting and resuming the session in 755 ms shardId=1 closeCode=4000 attempt=1 delayMs=755 reason=closed classification=closed next=resume
2026-09-27 03:14:22.999 ✓ INFO lifecycle [lifecycle.ready] Shard 1 resumed its session after 766 ms offline shardId=1 attempt=2 durationMs=1 mode=resume shards=2
2026-09-27 03:14:23.737 ℹ INFO lifecycle [lifecycle.stopRequested] The signal passed to runBot was aborted, so the bot is shutting down
2026-09-27 03:14:23.739 ℹ INFO lifecycle [lifecycle.shutdown] Shutting down
2026-09-27 03:14:23.742 ✓ INFO lifecycle [lifecycle.shutdownComplete] Shutdown complete in 3 ms durationMs=3
```
When a stream is not a terminal, such as under a process manager or in a container, its records are printed as one JSON object per line instead. Standard output and standard error decide separately. Set `format` to choose explicitly, or set the `FLUXERLY_LOG_FORMAT` environment variable to `pretty` or `json` for a client without `format`. A [supervisor](https://fluxerly.neontechspace.com/docs/glossary.md#supervisor) forwards child records as JSON and reconstructs the same pretty lines, including `Hint`, `Retry` and `Validation` rails, in the format of the stream they go to
Readable output uses ANSI color, Unicode icons and vertical gutter rails on a terminal, falling back to ASCII symbols when Unicode is unavailable and to plain text without icons or rails when color is off. Set `FLUXERLY_LOG_COLOR` to `1`, `true`, `yes` or `on` to force color, or to `0`, `false`, `no` or `off` to turn it off. Any non-empty `NO_COLOR` value, such as `NO_COLOR=1`, disables color even when `FLUXERLY_LOG_COLOR` is set, while an empty `NO_COLOR=""` leaves automatic color enabled. Setting `FORCE_COLOR=0` or `TERM=dumb` disables automatic color. Standalone formatting with `describeError(error, { color: "auto" })` or `report.describe({ color: "auto" })` follows the same terminal and environment rules on standard error, and defaults to plain text (`color: false`)
A failed handler is printed at Error with its message, stack and cause chain, because the error came from the bot's own code. When the indented error follows on the next line, the header line omits the duplicated error summary. Names, application error codes, messages and stacks, including causes, mask recognized credentials: Authorization, Proxy-Authorization, Cookie, Set-Cookie and X-API-Key headers, a value after a name ending in `token`, `secret`, `password`, `passwd`, `secretAccessKey`, `privateKey` or API key, written as `api_key`, `apiKey` or `X-API-Key`, in forms such as `password=x`, `"apiKey": "x"` or `secret: 'x'`, also in printed objects, voice keys such as `e2eeKey` and ICE credentials, OAuth authorization codes and PKCE `codeVerifier` values, signed JSON tokens such as JWTs, and in URLs the user name and password, invite codes, webhook tokens and the signatures of signed links, such as `X-Amz-Signature`, `X-Goog-Signature`, the `sig` of an Azure link, the `Signature` of a Google link and the `hm` of a Fluxer attachment link, also after a link is split into an object. A short value written another way, such as `token: abc` in a sentence, can stay readable, and another service's secret under a name not listed here may too. So do the bytes of a `Buffer` or `Uint8Array`, which print as numbers, and context the bot adds itself, such as Effect log annotations or a `ConfigurationError` hint. Stack frames inside the SDK and Effect collapse into one line, so the bot's own frames stand out
```text
2026-09-26 21:27:52.689 ✖ ERROR events [events.handlerFailed] The messageCreate handler failed event=messageCreate subscriptionId=messageCreate#1 messageId=1456074443980800005 channelId=1456074443980800002 guildId=1456074443980800001
│ ✖ TypeError: Cannot read properties of undefined (reading 'content')
│ at messageCreate (file:///srv/bot/bot.js:3:78)
│ ... 9 SDK and Effect frames hidden
```
An expected SDK error, such as a rejected request, prints its code, hint, safe details, retry guidance (`Retry:`) and any Fluxer field rejections (`Validation:`) instead of stack frames. Here a handler returned a failed reply because the bot lacks permission in the channel. For a missing permission, the hint and `requiredPermissions` name the permissions Fluxer checks for the operation, because Fluxer does not report which one is missing
```text
2026-09-26 21:27:52.804 ✖ ERROR events [events.handlerFailed] The messageCreate handler failed event=messageCreate subscriptionId=messageCreate#1 messageId=1456074443980800006 channelId=1456074443980800002 guildId=1456074443980800001
│ ✖ MessageError [message.send.rejected]: Message send failed: Fluxer reports that the bot lacks a required permission (MISSING_PERMISSIONS, HTTP 403)
│ → Hint: The bot needs View channel and Send messages for this operation. Grant them to the bot's role in the community settings or the channel's permission overrides. Embeds also need Embed links, files need Attach files, and a forward needs View channel in its source channel. In a thread, Send messages in threads in the parent channel replaces Send messages
│ Details: operation=send reason=rejected outcome=rejected status=403 apiError=MISSING_PERMISSIONS requiredPermissions=["ViewChannel","SendMessages"]
│ ↻ Retry: Do not retry unchanged
```
When Fluxer rejects individual request fields, a `Validation:` rail lists each field path, Fluxer validation code and explanation under `Retry:`, such as `embeds.0.title [CONTENT_EXCEEDS_MAX_LENGTH]: Submitted text exceeds Fluxer's limit`
A 401 or 403 rejection waits up to one second for its handler to finish. If the handler fails with that same rejection, directly or in its cause chain, before the Warn is logged and no `onError` hook is configured for that failure, only the handler's failure record appears. A handler that fails more than one second later also logs its failure, because the `rest.rejected` Warn has already appeared
Different requests with the same status and code remain separate rejections
When the handler handles such a rejection itself, or passes it to an `onError` hook, the `rest.rejected` Warn still appears, because it usually points at a token or permission problem that persists. Repeats of it [collapse](https://fluxerly.neontechspace.com/docs/logging.md#collapse-repeated-errors) like other Warn records. Each REST record also carries a monotonic per-client `requestId` (`#1` in colored output, `requestId=1` in plain text and JSON) to correlate attempts, retries, rate-limit waits, rejections and payload traces for one request, and actionable warnings render their top-level `hint` on an indented `→ Hint:` line
```text
2026-09-26 21:27:52.802 ▲ WARN rest [rest.rejected] POST /channels/:id/messages was rejected for channel 1456074443980800002: Fluxer reports that the bot lacks a required permission (MISSING_PERMISSIONS, HTTP 403) #1 route=/channels/:id/messages status=403 method=POST apiError=MISSING_PERMISSIONS
→ Hint: Grant the bot's role View channel and Send messages in this channel, plus Embed links or Attach files when the message has them, in the community settings or the channel's permission overrides
```
## Look up a record code
Every record has a stable code, shown in brackets in readable output. The [error and log codes](https://fluxerly.neontechspace.com/docs/codes/) page lists every code with its meaning and next step. These Warn records often surprise a new bot:
| Code | Meaning |
| --- | --- |
| `rest.rejected` | Fluxer rejected a request with HTTP 401 or 403, usually a token or permission problem, or a webhook client's token with HTTP 404. It is logged even when the application handles the Result. A handler that fails with the rejection within one second and has no `onError` hook logs only its own failure record. A later failure logs both. A bot that expects these rejections can set the `rest` [category](https://fluxerly.neontechspace.com/docs/logging.md#choose-levels-and-categories) to `error` |
| `rest.responseRejected` | A successful response to an SDK operation did not match the expected shape. The failing field is in `fields.field` |
| `sdk.unknownEnvironmentValue` | The `FLUXERLY_LOG_FORMAT` or `FLUXERLY_LOG_COLOR` variable has a value the SDK does not recognize, so it is ignored |
## Choose levels and categories
The default level is `info`. Set `level` for the whole client and `categories` for single areas. The categories are `lifecycle`, `gateway`, `rest`, `ratelimit`, `cache`, `events`, `commands`, `collectors`, `supervisor` and `sdk`
```ts
import { createClient } from "@neontechspace/fluxerly"
export function createQuietClient(token: string) {
return createClient({
token,
logging: {
level: "warn",
categories: { lifecycle: "info", rest: "debug" },
},
})
}
```
| Level | What appears |
| --- | --- |
| `fatal` | Only Fatal records. Failed handlers, failed hooks and cleanup failures are Error records, so this level hides them |
| `error` | Application errors, failed hooks, connections that cannot continue and cleanup failures |
| `warn` | Lost connections, session resets, rate-limit waits of one second or more, rejected requests and responses, skipped malformed gateway events and dropped events |
| `info` | Startup, shard readiness and shutdown with its duration |
| `debug` | Every REST request with its route template, status and duration, retries, gateway dispatch summaries, rejected and unmatched commands |
| `trace` | Heartbeats and every gateway opcode |
The `silent` level turns a category or the whole client off, including application errors that have no `onError` hook and unsafe payload records
To change levels while the bot runs, for example to investigate a problem without a restart, pass new `level` and `categories` settings to `client.logging.configure`. Omitted `level` and `categories` return to their defaults. A `debug` setting there replaces the current Debug categories, as described in [Turn on debug output without changing code](https://fluxerly.neontechspace.com/docs/logging.md#turn-on-debug-output-without-changing-code), and an omitted one keeps them. The other `logging` settings stay as the client was created
```ts
import type { Client } from "@neontechspace/fluxerly"
export function traceRequests(client: Client) {
client.logging.configure({ level: "warn", categories: { rest: "debug" } })
}
```
## Turn on debug output without changing code
Set the `FLUXERLY_DEBUG` environment variable before starting the bot. The value `1` enables Debug records for every category, while a comma-separated list such as `gateway,rest` enables only those. The variable is read when the client is created
```text
FLUXERLY_DEBUG=rest,ratelimit node bot.js
```
The `debug` option does the same from code, with `true` or a list of categories. Debug settings only lower a threshold, so `level: "silent"` with `FLUXERLY_DEBUG=rest` still prints REST Debug records
To change Debug output while the bot runs, pass `debug` to `client.logging.configure`. It replaces the categories chosen at creation, including those from `FLUXERLY_DEBUG`, and `debug: false` turns them all off
```ts
import type { Client } from "@neontechspace/fluxerly"
export function stopDebugOutput(client: Client) {
client.logging.configure({ debug: false })
}
```
## Handle failures in one place
Pass `onError` to receive every failure that has no returned result: Handler and command failures, [collector](https://fluxerly.neontechspace.com/docs/glossary.md#collector) callbacks and filters, cleanup progress callbacks, subscriptions closed by a full queue with `overflow: "stop"`, message cache callbacks and failed state observers. The report holds the original error and the IDs of the message involved. The SDK adds no message content itself, but an error from the bot's own code can contain some. With a hook in place the SDK keeps those failures at Debug instead of printing them again
```ts
import { runBot } from "@neontechspace/fluxerly"
export function runReportedBot(token: string | undefined, report: (text: string) => void) {
return runBot({
token,
onError: (failure) => report(failure.describe()),
events: {
messageCreate: ({ message, reply }) => {
if (message.content !== "!ping") return undefined
return reply("Pong!")
},
},
})
}
```
A subscription's own `onError` takes precedence for that subscription. Pass `{ color: "auto" }` to `failure.describe()` for ANSI styling, icons and gutter rails only when standard error is a terminal and color is not disabled by `NO_COLOR`, `FORCE_COLOR=0` or `TERM=dumb`, or `{ color: true }` to force styling. The [reliability guide](https://fluxerly.neontechspace.com/docs/reliability.md#report-failures-that-have-no-result) explains which failures produce reports
How reports are delivered
A failure only queues its report, so a slow hook never holds up event handlers. Reports are delivered one at a time in order. Up to 256 wait while the hook is busy, and later ones are logged instead and counted in `diagnostics().counters.reportsDropped`
A hook that throws or rejects is logged together with the original failure and is not retried. Shutdown does not wait for a hook that never finishes, and logs the reports it had not delivered with a note. The record's `fields.reportOutcome` names why a report was logged instead of delivered: `queueFull`, `interrupted`, `clientClosed` or `subscriptionClosed`
## Send records to an existing logger
The `sink` option replaces the console output. It receives frozen `LogRecord` objects with a stable `code`, a readable `message`, optional top-level `hint` and monotonic per-client `requestId` (correlating one REST request across attempts, retries, rate limits and payloads), and optional facts such as `shardId`, `route`, `event`, `command`, `status`, `closeCode`, `delayMs`, `durationMs` and `error`. When an Effect failure has more than one reason, such as a task whose cleanup also failed, `otherErrors` lists the rest. Other facts are in `fields`, such as `next` on `lifecycle.retry` and `lifecycle.connectionLost` records, which is `resume` when the next attempt resumes the session and `identify` when it starts a new one
Each `ErrorInfo` on `record.error` and `record.otherErrors` carries `origin`, `name`, `message`, optional `code`, `hint`, `retryable`, `retryAfterMs`, masked `validationErrors` (`path`, `providerCode`, `explanation`, capped at 32 items), `details`, `stack`, `cause` and `errors`. These structured fields are preserved in JSON logs, custom sinks, Effect log annotations and supervised child pretty logs, so log pipelines and coding agents can match on `code`, `hint`, `requestId` and `ErrorInfo` fields rather than parsing log prose, because message wording can change between releases
Many loggers have one method per level that takes an object of fields and a message. This sink passes each record to such a logger
```ts
import { createClient, type LogRecord } from "@neontechspace/fluxerly"
/** A logger with one method per level, each taking fields and a message */
interface LevelLogger {
trace(fields: object, message: string): void
debug(fields: object, message: string): void
info(fields: object, message: string): void
warn(fields: object, message: string): void
error(fields: object, message: string): void
fatal(fields: object, message: string): void
}
export function createLevelLoggerClient(token: string, logger: LevelLogger) {
return createClient({
token,
logging: {
sink: (record: LogRecord) => {
const { level, message, ...fields } = record
logger[level](fields, message)
},
},
})
}
```
Other loggers take one entry with the level inside it. This sink passes the whole record and maps `fatal` to `error` for loggers without a fatal level
```ts
import { createClient } from "@neontechspace/fluxerly"
/** A logger with one log method that reads the level from the entry */
interface EntryLogger {
log(entry: { level: string; message: string; [key: string]: unknown }): void
}
export function createEntryLoggerClient(token: string, logger: EntryLogger) {
return createClient({
token,
logging: {
sink: (record) => logger.log({ ...record, level: record.level === "fatal" ? "error" : record.level }),
},
})
}
```
A sink runs synchronously and its return value is ignored. A sink that throws or returns a rejected Promise is counted in `diagnostics().counters.sinkFailures` and reported once on standard error, and SDK work continues. Pass an array to use several sinks
## Collapse repeated errors
Identical Warn, Error and Fatal records within one minute are printed once. Records about different shards, subscriptions, routes or commands are not identical, so each one's first occurrence is printed. The next identical record after the window says how many were hidden, as in `(repeated 12× since last shown)`, and shutdown prints any remainder
A sink finds that count in `fields.repeated`. Change the window with `dedupe: { windowMs: 10_000 }` or turn collapsing off with `dedupe: false`. Counters in `diagnostics().counters` still include every occurrence
## Count what happened
The `client.diagnostics().counters` object keeps running totals since the client was created: Handler and hook failures, dropped events by reason and by event name, rejected gateway messages, unknown dispatches and opcodes, REST retries, rate-limit waits, reconnects, resumes, sink failures, cleanup failures and command rejections
The `eventsDroppedByEvent` object counts the same drops by event name, such as `messageCreate`, so a bot can see which handler loses events. Drops that have no known event name appear only in the reason totals of `eventsDropped`, so the per-event sum can be lower
```ts
import type { Client } from "@neontechspace/fluxerly"
export function healthSnapshot(client: Client) {
const { counters, state } = client.diagnostics()
return {
state,
reconnects: counters.reconnects,
droppedEvents: Object.values(counters.eventsDropped).reduce((total, count) => total + count, 0),
handlerFailures: counters.handlerFailures,
}
}
```
## Debug payloads safely
The setting `unsafe: { payloads: true }` adds Trace records with gateway and REST payload bodies, for all categories or the listed ones. Payloads can contain private message content, so the client prints a Warn banner once, at startup or before the first payload record, even when the level hides warnings
A category set to `silent` prints no payloads, and a received REST body shows at most its first 64 KiB. Received bodies are printed only for accepted responses. A rejected request's Fluxer code and message are in its error. Masking still applies: Values under keys ending in `token`, `secret`, `password`, `passwd`, `secretAccessKey`, `privateKey` or API key, written as `api_key`, `apiKey` or `X-API-Key`, Authorization and Cookie values, client secrets, the signed upload URL of an attachment upload plan, the user name and password in a URL such as `https://user:password@host/path`, and invite codes in invites, invite audit entries, vanity URL fields and invite links, including in truncated JSON text. Leave it off in production
```ts
import { createClient } from "@neontechspace/fluxerly"
export function createPayloadDebugClient(token: string) {
return createClient({ token, logging: { unsafe: { payloads: true, categories: ["gateway"] } } })
}
```
## Use the Effect logger in native programs
A native client, created from the [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect) entry point `@neontechspace/fluxerly/effect`, sends records through the running program's Effect logger with `Effect.logWithLevel`. Each record carries `fluxerly.*` annotations such as `fluxerly.code`, `fluxerly.category`, `fluxerly.hint`, `fluxerly.requestId` and `fluxerly.shardId`, so any Effect logger, span and tracer applies. Records with errors also carry a `Cause` with recognized credentials masked, as in printed records
A record with an SDK error also carries `fluxerly.error.code`, `fluxerly.error.hint`, `fluxerly.error.retryable`, `fluxerly.error.retryAfterMs`, JSON-encoded `fluxerly.error.validationErrors` when Fluxer reports field errors, and one `fluxerly.error.` annotation per safe detail, such as `fluxerly.error.status`. Each error in its cause chain adds the same annotations with one more `cause.` in the prefix, such as `fluxerly.error.cause.code`, `fluxerly.error.cause.hint` and `fluxerly.error.cause.`, and any additional `otherErrors` entries appear under `fluxerly.otherErrors..*`
Native clients accept the same `logging` settings. A `sink` or an explicit `format` replaces the Effect logger with SDK output
```ts
import { Effect, Logger } from "effect"
import { createClient } from "@neontechspace/fluxerly/effect"
export function runNativeBot(token: string, signal: AbortSignal) {
const program = Effect.scoped(
Effect.gen(function* () {
const client = yield* createClient({ token, logging: { categories: { rest: "debug" } } })
yield* client.run()
}).pipe(Effect.withLogger(Logger.consoleJson), Effect.annotateLogs("bot", "gateway")),
)
return Effect.runPromise(program, { signal })
}
```
Debug and Trace records chosen by the SDK settings bypass the Effect minimum log level, while Info and higher records still respect it
## Export metrics and traces with OpenTelemetry
Pass an `observe` function to the client to receive a measurement each time the SDK finishes a piece of work: A REST request attempt with its method, route template, status and duration, a rate-limit wait, a reconnection attempt, a resumed session, and a handler or command run with its duration and outcome
Each measurement is an `Observation` whose `type` field says which kind it is. Observations never contain tokens, payloads or message content, so they can go to any monitoring system. Both entry points accept the same option
A command router emits one handler observation per message, including event and command middleware in its duration. A matched command supplies its canonical name in `command`, even when a guard denies it or middleware stops it. A reported failure gives `outcome: "failure"` even if middleware recovers, interruption gives `"cancelled"`, and other completions give `"success"`. Messages with no command match still produce an observation without `command`
This example records durations and reconnection attempts with an OpenTelemetry meter. The `Meter` interface lists only the methods the example calls, so the code needs no extra package, and the meter from `metrics.getMeter("bot")` in `@opentelemetry/api` fits it
```ts
import { runBot, type Observation } from "@neontechspace/fluxerly"
type Attributes = Record
/** The parts of an OpenTelemetry Meter this bot uses */
interface Meter {
createHistogram(name: string, options?: { unit?: string }): {
record(value: number, attributes?: Attributes): void
}
createCounter(name: string): { add(value: number, attributes?: Attributes): void }
}
export function meterObserver(meter: Meter) {
const requests = meter.createHistogram("bot.rest.duration", { unit: "ms" })
const handlers = meter.createHistogram("bot.handler.duration", { unit: "ms" })
const reconnects = meter.createCounter("bot.gateway.reconnects")
return (observation: Observation) => {
if (observation.type === "rest")
requests.record(observation.durationMs, {
method: observation.method,
route: observation.route,
status: observation.status ?? "none",
})
else if (observation.type === "handler")
handlers.record(observation.durationMs, {
event: observation.event,
...(observation.command === undefined ? {} : { command: observation.command }),
outcome: observation.outcome,
})
else if (observation.type === "reconnect") reconnects.add(1, { shard: observation.shardId })
}
}
export function runObservedBot(token: string | undefined, meter: Meter) {
return runBot({ token, observe: meterObserver(meter), events: {} })
}
```
The SDK calls `observe` while it finishes the measured work, so the function should only record values and leave sending them to the exporter. An `observe` function that throws does not change what the bot does, and each throw is counted in `diagnostics().counters.sinkFailures`
In a native program, the SDK also opens spans named `fluxerly.gateway.connect`, `fluxerly.rest.request`, `fluxerly.event.handle` and `fluxerly.command.execute`, and updates the metrics `fluxerly_rest_duration_ms`, `fluxerly_ratelimit_wait_ms`, `fluxerly_gateway_reconnects_total`, `fluxerly_events_dropped_total` and `fluxerly_handler_failures_total`. The dropped-events metric carries the attribute `reason` and, where the event name is known, `event`
A command span covers its middleware, guards, argument conversion, cooldown and execution. Command failure metrics use the canonical command name
Without a metric exporter, metrics stay in memory. Provide the Layer from `@effect/opentelemetry`, the Effect value that supplies the exporter, to the native program to export them
```ts
import { Effect, type Layer } from "effect"
import { runBot } from "@neontechspace/fluxerly/effect"
/** Pass the tracing Layer built with @effect/opentelemetry, such as its NodeSdk layer */
export function runTracedBot(token: string | undefined, telemetry: Layer.Layer) {
return runBot({ token, processSignals: true, events: {} }).pipe(Effect.provide(telemetry))
}
```
Use [`client.diagnostics()`](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#diagnostics) for a current snapshot of connection state, request counts and cache accounting, and the [troubleshooting guide](https://fluxerly.neontechspace.com/docs/troubleshooting.md) to match common log lines with fixes
---
# Send messages, embeds and files
Reply, send and edit messages, build embeds, attach files and send direct messages
Start with a bot that can reply to `!ping`. Add these helpers to the [first bot example](https://fluxerly.neontechspace.com/docs/quick-start.md) and call them from a command or message [handler](https://fluxerly.neontechspace.com/docs/glossary.md#handler). They use the bot's existing `client` rather than opening another connection. The [last section](https://fluxerly.neontechspace.com/docs/messages.md#wire-it-up) shows where they plug into `runBot`
## Reply to a message and check what happened
Use `reply` when the answer belongs to an incoming message. Awaiting an operation in the default API gives a [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result): Check `isErr()` first, then read `value`
```ts
import { describeError, type Client, type Message } from "@neontechspace/fluxerly"
export async function replyHello(client: Client, message: Message) {
if (message.author.isBot) return
const result = await client.messages.reply(message, `Hello, ${message.author.username}!`)
if (result.isErr()) {
console.error(describeError(result.error))
return
}
return result.value
}
```
A plain string sends a text-only message. On success, `value` is the message Fluxer created, including its ID. The `describeError` helper prints the failure's message, code, suggested fix and cause. Replies do not notify anyone by default, not even the author of the replied-to message
What does a failed send say?
The error message names the operation and Fluxer's answer, then Fluxer's code and the HTTP status, for example `Message send failed: Fluxer reports that the bot lacks a required permission (MISSING_PERMISSIONS, HTTP 403)`. The error's `hint` suggests a next step. For a missing permission, `details.requiredPermissions` lists the permissions Fluxer checks for the operation, such as `["ViewChannel", "SendMessages"]` for a send, and the hint names them
Fluxer does not report which one is missing, so the bot may already have some of them. When Fluxer answers with a code this SDK version does not know yet, `details.providerCode` holds it. When Fluxer's answer does not have the expected shape, `details.responseField` names the field that failed
A rejection with HTTP 401 or 403 that the application handles also logs a Warn record with the code `rest.rejected`, because it usually points at a lasting token or permission problem. The SDK holds that Warn for up to one second. A handler's failure record replaces it only if the handler fails with the same rejection while the Warn is held and no `onError` hook is configured for that failure
[Identical repeats collapse](https://fluxerly.neontechspace.com/docs/logging.md#collapse-repeated-errors) into one record per minute by default. The [error and log codes](https://fluxerly.neontechspace.com/docs/codes/) page lists every code with its meaning
Skip join notices and other system messages
Fluxer also delivers notices, such as a member joining or a pinned message, as messages. Compare `message.type` with a `MessageType` constant to tell them apart. For example, `message.type === MessageType.UserJoin` is a join notice, and ordinary messages are `MessageType.Default` or `MessageType.Reply`
A `messageCreate` or `messageUpdate` event for a community message can carry `message.member`, the author's community membership as Fluxer held it when it sent the event, with roles, nickname and join time. It is absent on messages from REST reads, direct messages, webhooks and authors who left the community, and the message cache does not keep it, so read it in the handler
With `cache.members` enabled, `members.get` then answers for that author without a request. The same member arrives as `reaction.member` on `messageReactionAdd` and `messageReactionRemove` events and as `typing.member` on `typingStart` events. A member that Fluxer sends in a form the SDK cannot read is left off, and the event still arrives
A `messageCreate` event, and no other message event, can also carry `message.channelType`, the numeric type of the channel, with 1 for a direct message and 3 for a group direct message, `message.mentionedHere`, which Fluxer sends only as `true` for a here mention, and `message.nicknames`, the nicknames of a group direct message keyed by user ID
REST reads and `messageUpdate` events never carry them, and the message cache does not keep them. A `messageDelete` event can carry `deletion.member`, the author's community membership without a username or bot flag, because Fluxer removes the member's user from it. The member cache does not store it
Received messages can carry `message.messageReference`, which points at a replied-to or forwarded message, or at the source of an announcement copy or follow notice. Its `channelId` is always present, but `id` is optional. Check `id`, then build a `MessageReference` from both fields for a fetch or reply. A follow notice identifies only the source channel. See [announcement channels](https://fluxerly.neontechspace.com/docs/announcement-channels.md) for publishing messages and handling their copies
Sends and edits accept `MessageFlags.SuppressEmbeds` and `MessageFlags.SuppressNotifications`. Message sends also accept `MessageFlags.VoiceMessage` for a [voice note](https://fluxerly.neontechspace.com/docs/messages.md#mark-media-as-explicit-or-send-a-voice-note). Message sends include replies, direct messages, the first message of a forum post and webhook sends. Edits and webhook forwards reject that flag, and the SDK rejects any other flag before sending the request. Fluxer sets `Crossposted`, `IsCrosspost` and `SourceMessageDeleted` itself
## Mention someone deliberately
Create a mention with `format.userMention`, then allow a notification for that specific user. Role and channel mentions have matching `roleMention` and `channelMention` helpers
```ts
import { format, type Client } from "@neontechspace/fluxerly"
export async function notifyParticipant(client: Client, channelId: string, userId: string) {
return await client.messages.send(channelId, {
content: `${format.userMention(userId)} The game is starting`,
allowedMentions: { users: [userId] },
})
}
```
Methods that take a user, role or channel ID expect the decimal ID as a string and trim surrounding whitespace first, as Fluxer does. To read a mention typed by a user, use `format.tryParseMention`, which returns a Result instead of throwing on invalid text. [Command arguments](https://fluxerly.neontechspace.com/docs/commands.md) can also accept either an ID or a mention
Send a text-to-speech message
Add `tts: true` to the content passed to `messages.send`, `messages.reply`, `directMessages.send` or the `reply` helper of a `runBot` handler or command. A value other than a boolean fails with reason `input` before any request.
In a community, a bot without the Send TTS Messages permission gets a normal message and no error
The `tts` field of a message is meaningful only on the message returned by the send and on the `messageCreate` event. Fluxer does not store it, so fetches, history pages and other later reads always report `false`.
Webhook messages do not accept `tts`: A webhook send, reply or forward that includes it fails with reason `input` before any request
## Send, then edit the returned message
Use `send` for a channel message that does not reply to anything. Keep the returned message to edit it later
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function postStatus(client: Client, channelId: string) {
const sent = await client.messages.send(channelId, "Preparing the report…")
if (sent.isErr()) return sent
return await client.messages.edit(sent.value, "Report ready")
}
```
The helper posts a message, then edits it, and returns the edit's Result or the send's failure
What if the send or the edit fails?
If the edit fails, the first message stays posted. If the connection fails after a send or edit was dispatched, the change may still have reached Fluxer. Check the returned Result before deciding whether to try again, and avoid repeating a write whose outcome is unknown.
The [reliability guide](https://fluxerly.neontechspace.com/docs/reliability.md) explains these uncertain writes and when a retry is safe
## Build an embed
An [embed](https://fluxerly.neontechspace.com/docs/glossary.md#embed) is a formatted card with a title, description, color and fields. The embed builder assembles one step by step. Pass the builder in the message's `embeds` list
```ts
import { builders, type Client } from "@neontechspace/fluxerly"
export async function postSchedule(client: Client, channelId: string) {
const embed = builders.embed()
.title("Tonight's game")
.description("Meet in the lobby before the first round")
.color("#8b7cf8")
.field("Start", "19:00 UTC", { inline: true })
.field("Mode", "Co-op", { inline: true })
.footer({ text: "Snacks provided" })
return await client.messages.send(channelId, { embeds: [embed] })
}
```
The `inline` option places fields side by side. The `color` method accepts a hex string such as `"#8b7cf8"`, a number or an RGB tuple, and `timestamp` accepts a `Date`, epoch milliseconds or an ISO 8601 string with a time zone
The send checks the embed against Fluxer's limits. It reads the builder once, so later builder changes do not alter the sent message. Use `messages.edit` for that. The builder's `build()` method returns the same embed as a plain object, which could also be written by hand
Embed URLs, a link channel's `url` and a webhook message's `avatarUrl` must start with `http://` or `https://`, and their host must be an IP address or a domain name with a top-level domain, such as `example.com`. A host such as `localhost` fails with reason `input` before any request, as hosted Fluxer refuses it. A client or webhook client created with a custom `instance` skips only the top-level domain rule locally and leaves it to that server, because a Fluxer server in development mode accepts such hosts
An embed's `image.url` or `thumbnail.url` can use `attachment://filename` to show a new image or video uploaded in the same request. Avoid two dots in a row and names such as CON or AUX, because Fluxer renames those files and the reference then fails. The name must equal the name Fluxer stores for at least one upload, including case, and when several uploads share it Fluxer shows the last one. Its extension must map to an image or video MIME type in Fluxer's filename lookup, such as AVIF or MP4. Without an `attachments` list, an edit may also name a file already attached, which Fluxer moves into the embed. A kept attachment ID cannot supply the URL
In a community channel, sending or editing a message with embeds needs the `EmbedLinks` permission. New communities grant it to everyone, but where it is removed, Fluxer rejects the whole message with a missing-permissions error instead of sending it without the embeds
## Upload a small generated file
For text already in memory, encode it to bytes and give the attachment a file name. No temporary file on disk is needed
```ts
import { builders, type Client } from "@neontechspace/fluxerly"
export async function sendChecklist(client: Client, channelId: string) {
const data = new TextEncoder().encode("[ ] Check permissions\n[ ] Test !ping\n")
const message = builders.message()
.content("Bot checklist")
.attachment({ data, filename: "checklist.txt", contentType: "text/plain" })
.build()
return await client.messages.send(channelId, message)
}
```
The builder keeps a reference to the bytes, and the send copies them when it is called. For larger files, pass a `file` source such as a `Blob`, or a `stream` with its exact `size`, instead of `data`. The [attachment input reference](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#attachmentinput) lists these forms, which avoid loading everything into memory
## Send a file from disk
On Node.js, `openAsBlob` from `node:fs` opens a file without reading it into memory. Pass the result as `file` and give the upload a name. A path string is not accepted, so open the file first
```ts
import { openAsBlob } from "node:fs"
import { basename } from "node:path"
import { builders, type Client } from "@neontechspace/fluxerly"
export async function sendReport(client: Client, channelId: string, path: string) {
const file = await openAsBlob(path)
const message = builders.message()
.content("Daily report")
.attachment({ file, filename: basename(path) })
.build()
return await client.messages.send(channelId, message)
}
```
The send reads the file while it uploads, so keep the file unchanged until the send finishes
## Mark media as explicit or send a voice note
Set `explicitMedia: true` on an attachment to mark it as sensitive, next to `spoiler`. Fluxer's apps then treat it like media that Fluxer's own check flags. The mark does not make Fluxer refuse the file. Fluxer still checks media itself and refuses explicit media where the community's explicit content filter applies, with `apiError.code` `explicitContentCannotBeSent`
On a received attachment, the explicit-media mark is `(attachment.flags & (1 << 4)) !== 0`. It can be present even when `attachment.nsfw` is false or absent
A voice note is an uploaded audio file that Fluxer's apps show with a player and a waveform. It is separate from live voice channels, where `client.voice` handles gateway signaling while built-in audio transport waits for Fluxer's upcoming native voice engine. Send one with `MessageFlags.VoiceMessage` and exactly one audio attachment that has `duration` in whole seconds and `waveform`, the Base64 amplitude bytes the player draws. The SDK does not record or decode audio. Decode the file into the samples of its first channel, the one Fluxer's apps read, and `voiceWaveform(samples, sampleRate)` computes both values the way Fluxer's apps do, so the bars match a note recorded in Fluxer
```ts
import { MessageFlags, voiceWaveform, type Client } from "@neontechspace/fluxerly"
// The samples are one channel of the decoded file, at sampleRate samples per second
export async function sendVoiceNote(client: Client, channelId: string, audio: Uint8Array, samples: Float32Array, sampleRate: number) {
return await client.messages.send(channelId, {
attachments: [{ data: audio, filename: "note.ogg", contentType: "audio/ogg", ...voiceWaveform(samples, sampleRate) }],
flags: MessageFlags.VoiceMessage,
})
}
```
With ffmpeg, `ffmpeg -i note.ogg -af 'pan=mono|c0=c0' -ar 48000 -f f32le -` writes the first channel as 32-bit float samples at 48,000 samples per second. Mixing the channels, as `-ac 1` does, gives other bars for a stereo file. Copy the output into a `Float32Array`, for example with `new Float32Array(new Uint8Array(output).buffer)`, and pass 48000 as the rate. Exact parity with Fluxer's apps needs the same first-channel samples at the same sample rate, which another decoder or resampling can change slightly. Ordinary decoded sample scales work, such as floats from -1 through 1 or 16-bit integers from a WAV file, because the waveform is relative to the loudest part
A voice note cannot have visible content, embeds or stickers, and the SDK refuses those before sending. Blank content or only invisible characters, such as a zero-width space, still count as no content. Fluxer also checks that the file is audio and that it is no longer than the instance allows, 1,200 seconds by default. The `messages.send` and `messages.reply` methods, direct message sends, the first message of a forum or media post and webhook sends and replies accept voice notes. A waveform holds at most 4,096 characters, except in a webhook send or reply. Webhook files always go as multipart, where Fluxer reads a waveform of at most 256 characters, so a longer waveform fails locally on `attachments[].waveform`. A `voiceWaveform` result fits for audio up to 19.2 seconds, and `voiceWaveform(samples, sampleRate, { maxPoints: 192 })` fits for audio of any length. For audio over 19.2 seconds, each of its bars covers more audio than in a note recorded in Fluxer. Edits and webhook forwards do not accept voice notes. To keep an existing voice note as a voice note, omit `flags` when editing it. On the bot's own message, and on a webhook message edited through its webhook, supplying flags, including 0, clears its voice-note flag, and an edit cannot set it again. When the bot client edits another author's message, Fluxer requires Manage Messages in a community and changes only `SuppressEmbeds`, keeping the other flags
## Download an attachment when needed
Received messages describe their attachments but do not download them. Set a byte limit and handle a failed download before processing any content
```ts
import { describeError, type Client, type Message } from "@neontechspace/fluxerly"
export async function readFirstSmallFile(client: Client, message: Message) {
const attachment = message.attachments[0]
if (!attachment) return
const downloaded = await client.attachments.download(attachment, { maxBytes: 64 * 1024 })
if (downloaded.isErr()) {
console.error(describeError(downloaded.error))
return
}
return downloaded.value
}
```
Check the file type and contents before processing downloaded bytes. The download uses the attachment's media address on the bot's Fluxer instance and does not accept arbitrary URLs from message text
Buffered downloads and `attachments.stream` preserve a sanitized cause for discovery and transport failures, including a safe code such as `ECONNRESET` when available. The original transport error, attachment URL and response body are not retained in that cause
Attachment links can expire while the file still exists. The SDK does not refresh links automatically. Before downloading a stored link, call `attachments.refreshUrls` and use the returned URL. Refreshing does not restore a deleted file
```ts
import type { Attachment, Client } from "@neontechspace/fluxerly"
export async function downloadStored(client: Client, attachment: Attachment) {
if (attachment.url === undefined) return
const refreshed = await client.attachments.refreshUrls([attachment.url])
if (refreshed.isErr()) return refreshed
const url = refreshed.value[0]?.refreshed ?? attachment.url
return client.attachments.download({ ...attachment, url }, { maxBytes: 64 * 1024 })
}
```
The same steps in the Effect API:
```ts
import { Effect } from "effect"
import type { Attachment, Client } from "@neontechspace/fluxerly/effect"
export const downloadStored = (client: Client, attachment: Attachment) =>
Effect.gen(function* () {
if (attachment.url === undefined) return
const [link] = yield* client.attachments.refreshUrls([attachment.url])
const url = link?.refreshed ?? attachment.url
return yield* client.attachments.download({ ...attachment, url }, { maxBytes: 64 * 1024 })
})
```
## Send a requested direct message
Send a private message only after the recipient asks for one, for example through an opt-in command. The `directMessages.send` method opens the conversation with that user and sends the message
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function sendRequestedDm(client: Client, recipientId: string) {
return await client.directMessages.send(recipientId, "The requested game instructions are ready")
}
```
A send can still fail when the recipient's privacy settings block it. To reuse the conversation, `directMessages.open` returns its channel, and existing group conversations use the normal message methods with their channel ID. No method creates a group conversation. Fluxer lets a bot create one with `client.rest.call` and `POST /users/@me/channels` with a `recipients` list, for people who share a community with the bot and allow it. Where the instance turns on CAPTCHA, Fluxer also asks for a solved challenge, which the SDK cannot send, so it fails with `apiError.code` `captchaRequired`. See [private conversations](https://fluxerly.neontechspace.com/docs/api/js-ts/users-and-dms/#directmessages) for reads and permitted management actions
## Wire it up
In a `runBot` bot, each command receives a `reply` helper already bound to the incoming message. This bot answers `!schedule` with an embed and stops cleanly on Ctrl+C
```ts
import { builders, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
schedule: {
description: "Show tonight's game",
execute: ({ reply }) => {
const embed = builders.embed()
.title("Tonight's game")
.description("Meet in the lobby before the first round")
.color("#8b7cf8")
return reply({ embeds: [embed] })
},
},
},
},
})
```
Returning the reply's Result lets the [command router](https://fluxerly.neontechspace.com/docs/glossary.md#command-router) report a failed reply with the command name. If the bot itself stops with a failure, such as a rejected token, `runBot` logs it once and sets `process.exitCode` to 1, so the file needs no error handling of its own
Helpers that take a `client`, such as `postSchedule` above, receive it from the command context, for example with `execute: ({ client, message }) => postSchedule(client, message.channelId)`
Continue with [prefix commands](https://fluxerly.neontechspace.com/docs/commands.md) to turn these helpers into named bot actions, or see the [Effect workflow examples](https://fluxerly.neontechspace.com/docs/effect-workflows.md) for the same operations inside an Effect program
---
# Production checklist
Check a bot before it runs unattended, with the guide section that explains each item
## Before the first start
- Run Node.js 26.13 or newer
- Read the token from `process.env.FLUXER_BOT_TOKEN`, never from a source file or an image
Explained in: [Runtime requirements](https://fluxerly.neontechspace.com/docs/support-and-compatibility.md#runtime-and-upgrade-requirements) · [Preparing the bot](https://fluxerly.neontechspace.com/docs/deploying.md#prepare-the-bot)
## Failures
- Return or check every [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result), the success or failure each request gives, so a failed send is reported instead of lost
- Send failures somewhere someone reads, with an `onError` hook or a log sink
- Do not resend a write whose outcome is unknown
- Leave rate limits to the SDK, which waits for HTTP 429 on its own
Explained in: [Returning the Result](https://fluxerly.neontechspace.com/docs/reliability.md#return-the-replys-result) · [Failures in one place](https://fluxerly.neontechspace.com/docs/logging.md#handle-failures-in-one-place) · [An existing logger](https://fluxerly.neontechspace.com/docs/logging.md#send-records-to-an-existing-logger) · [Sending once](https://fluxerly.neontechspace.com/docs/reliability.md#send-once-when-the-outcome-is-uncertain) · [Retry rules](https://fluxerly.neontechspace.com/docs/reliability.md#limits-and-retry-rules)
## Running unattended
- Turn on only the caches the bot reads, and size them for its communities
- Give the process manager a stop timeout of about 30 seconds
- Restart after a crash with a delay
- Add a session store, so a quick restart resumes and gets the events it missed
- Watch the connection and each event subscription the bot cannot work without, which `runBot` already does
Explained in: [Cache settings](https://fluxerly.neontechspace.com/docs/configuration.md#cache) · [Shutdown](https://fluxerly.neontechspace.com/docs/deploying.md#what-happens-on-shutdown) · [Restart policy](https://fluxerly.neontechspace.com/docs/deploying.md#restart-policy) · [Resuming after a restart](https://fluxerly.neontechspace.com/docs/sharding.md#resume-after-a-restart) · [Watching the connection](https://fluxerly.neontechspace.com/docs/application-supervision.md#watch-the-connection-and-subscription)
## Before each deploy
- Run offline setup checks with [`fluxerly doctor --strict`](https://fluxerly.neontechspace.com/docs/cli.md#check-setup-offline-with-doctor)
- Run offline tests, as in [writing a first test](https://fluxerly.neontechspace.com/docs/testing.md#write-a-first-test)
---
# Start a bot
Send !ping and receive Pong! from a bot
Before starting, [create a Fluxer bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md), copy its token when Fluxer shows it and add the bot to a community. Fluxer shows a token only once, and the project below has a file for it. Fluxerly is tested against Node.js 26.13 or newer
## Generate the project
The generator writes into the terminal's current folder. Start in a new folder for the bot:
```sh
mkdir my-bot
cd my-bot
```
```sh
npx @neontechspace/fluxerly init
```
Adding `--template js`, `--template ts` or `--template effect` skips the question. The JavaScript and TypeScript templates write the bot shown below. The Effect template writes the [Effect starter bot](https://fluxerly.neontechspace.com/docs/effect-first-bot.md) instead. Each template includes a test and an `AGENTS.md` file, and creates a `.env` file with an empty token value unless that file already exists. The command then installs the dependencies and prints the remaining steps, or prints installation instructions when installation is skipped or fails
The folder may already hold the `.env` and `.gitignore` that the [manual setup](https://fluxerly.neontechspace.com/docs/quick-start.md#2-save-the-token) describes. The command keeps the `.env` and its token, adds `node_modules` and `.env` to the `.gitignore` when they are missing and leaves the rest of that file as it is. When any other file that the command writes already exists, such as `package.json` or `bot.js`, it stops without writing anything
Then set `FLUXER_BOT_TOKEN` in `.env` to the token. Check the bot with `npm test`, `pnpm test` or `bun run test`, which runs it against an in-memory Fluxer without the token or a network. Start it with `npm start`, `pnpm start` or `bun run start` and continue with [Try it](https://fluxerly.neontechspace.com/docs/quick-start.md#try-it). While changing the bot, start it with `npm run dev`, `pnpm dev` or `bun run dev` instead, which restarts it after each saved change
## Set up the project by hand
These steps create the same bot without the generator
### 1. Install the SDK
Open a terminal in the bot's folder.
Create a `package.json` file in that folder:
```json
{
"type": "module"
}
```
This lets the bot use `import` in Node.js
```sh
npm install @neontechspace/fluxerly
```
When a coding agent helps write the bot, copy the SDK's rules for it into the project's `AGENTS.md`, which many coding agent tools read automatically. Run the same command again after updating the SDK
```sh
npx --no fluxerly agents
```
### 2. Save the token
Save the token in a file named `.env` in the bot's folder:
```text
FLUXER_BOT_TOKEN=paste-the-token-here
```
Check that the file is named exactly `.env`. Some editors, such as Notepad, add `.txt` when saving, and Node.js cannot find `.env.txt`
Keep that file out of version control by adding this line to `.gitignore`:
```text
.env
```
### 3. Create the bot
Save this as bot.js.
The bot reads its token from `FLUXER_BOT_TOKEN` in the process environment, so the token never appears in the file
```js
import { defineBot, runBot } from "@neontechspace/fluxerly"
// The bot's options without its token, so its test can run them through createTestBot without a token or a network
export const bot = defineBot({
commands: {
prefix: "!",
commands: {
// Returning the reply reports a failed send to the log
ping: { execute: ({ reply }) => reply("Pong!") },
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main) await runBot({ token: process.env.FLUXER_BOT_TOKEN, ...bot })
```
The file exports the bot's options as `bot`. The `defineBot` function returns them unchanged and keeps the types of command arguments for TypeScript and editors. Running the file starts the bot with these options and the token, while a test can import `bot` without starting it. [Testing a bot](https://fluxerly.neontechspace.com/docs/testing.md) shows the test that the generator writes
### 4. Start it
Start the bot with the token's `.env` file:
```sh
node --env-file-if-exists=.env bot.js
```
When `FLUXER_BOT_TOKEN` is already set in the terminal, run the file without `--env-file-if-exists=.env` or keep the flag, which ignores a missing `.env` file
Set the variable in the terminal instead
In bash or zsh, run `export FLUXER_BOT_TOKEN="paste-the-token-here"`, then start the bot with `node bot.js` in the same terminal.
In PowerShell, run `$env:FLUXER_BOT_TOKEN = "paste-the-token-here"`, then `node bot.js`
The variable lasts until the terminal closes. The typed command can stay in the shell's history, so prefer `.env` on shared machines
## Try it
Once the bot is online, the terminal shows a line such as `Connected to Fluxer as MyBot in 1 community`. If it says instead that the bot is not in any community yet, open the link in that line to invite it
Type **!ping** in a channel the bot can read and reply to.
It should answer **Pong!**
The SDK skips messages from bots by default. The `commands` option routes a message that starts with the `!` prefix and a command name, such as `!ping`, to that command, and the bot ignores every other message
Press Ctrl+C to stop the bot. The SDK then stops the commands, closes the connection and finishes its cleanup before the program ends
## Keep going
Change `ping` or `Pong!` to customize the command or reply. Then choose a task:
- [Build a small bot](https://fluxerly.neontechspace.com/docs/small-bot.md): Combine commands, arguments, an embed, a welcome message, a permission check and a cooldown in one file
- [Learn the core concepts](https://fluxerly.neontechspace.com/docs/core-concepts.md): Clients, events, Results, caches and the gateway in plain terms
- [Copy an example bot](https://fluxerly.neontechspace.com/docs/examples.md): Complete bots for moderation, reaction roles, welcomes and tickets
- [Send messages, embeds and files](https://fluxerly.neontechspace.com/docs/messages.md): Check reply results, edit messages and attach a file
- [Add prefix commands to a bot](https://fluxerly.neontechspace.com/docs/commands.md): Register actions with typed arguments and generated help
- [React to events and collect replies](https://fluxerly.neontechspace.com/docs/events-and-collectors.md): Distinguish joins from startup and build a bounded conversation
- [Operate a long-running bot](https://fluxerly.neontechspace.com/docs/reliability.md): Handle failures, cancellation and shutdown
The [client's message methods](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#messages) link to the full API reference for exact inputs and return values
If the bot does not reply
Check that `FLUXER_BOT_TOKEN` is set and that the bot can view the channel and send messages. Without a token, the bot stops at once with an error whose hint points to an unset environment variable, which also happens when the terminal is not in the bot's folder or `.env` was saved as `.env.txt`. Keep the terminal running when trying `!ping`
When a reply fails, the terminal shows a log line with the reason and a hint, such as a missing permission. Outside a terminal, such as in an editor's run panel, log lines are JSON. Add `FLUXERLY_LOG_FORMAT=pretty` to `.env` for readable lines there. A reply can fail after Fluxer has already posted it, for example when the response is lost, so do not send it again blindly
The [troubleshooting guide](https://fluxerly.neontechspace.com/docs/troubleshooting.md) helps tell command, connection and request failures apart. Never share a bot token or private message contents
What happens when something fails?
Requests such as `reply` return expected failures in a Result, which is either a success or a failure. Unexpected SDK faults can still reject the Promise
The command returns the reply's Result, so the SDK logs a failed reply and the bot keeps running
A failure that stops the whole bot, such as a rejected token, is logged once, and the process ends with exit code 1 so a shell or process manager can tell it from a normal stop. A missing token is logged with a hint and also ends the process with exit code 1, before the bot connects. The [core concepts](https://fluxerly.neontechspace.com/docs/core-concepts.md) page explains Results in more detail
Using TypeScript or Effect?
Choose TypeScript above to save this example as `bot.ts`. The code is the same, and Node.js runs it directly, without a compilation step, and removes the types without checking them
A generated TypeScript or Effect project needs no further setup to typecheck. It installs TypeScript 7 and the Node.js types, writes the `tsconfig.json` below and adds a `check` script that runs the compiler, as `npm run check`, `pnpm run check` or `bun run check`.
To typecheck a project set up by hand, install the Node.js types, which the SDK's types use for values such as the `AbortSignal` passed to handlers:
```sh
npm install --save-dev @types/node
```
Install `typescript@7` the same way, as another development dependency. Then add a `tsconfig.json` next to the bot:
```json
{
"compilerOptions": {
"target": "ES2024",
"module": "NodeNext",
"types": ["node"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true
}
}
```
TypeScript only checks the code and writes no output, because Node.js removes the types itself. The last three settings keep the code in a form Node.js can run directly: Imports of other files may use their `.ts` extension, type-only imports need `import type`, and TypeScript features that generate code, such as `enum`, are reported. Run the check with `npm exec tsc`, `pnpm exec tsc` or `bun run tsc`
JavaScript can also use editor inference and optional `// @ts-check` without changing file extensions or adding a build step. Neither a compiler nor checked JavaScript is required to run the bot
The default API works with JavaScript and TypeScript. Effect is optional: The [Effect learning path](https://fluxerly.neontechspace.com/docs/effect-first-bot.md) introduces the native API and shows which Effect version to install
---
# Raw requests and raw events
Call a Fluxer route that has no method, and read a gateway event that has no typed event
Most bots never need this page. When a Fluxer route has no Fluxerly method, or a gateway event has no typed event, the SDK still gives a way in. The [endpoint map](https://fluxerly.neontechspace.com/docs/api/endpoints/) lists the routes that Fluxerly methods call, the other routes that accept the bot's token, and a few noted exceptions, with why the routes without a method rarely matter. It leaves out routes that need no token, such as sign-in, but `client.rest.request` can still send them
## Call a route without a method
A Fluxer route that has no Fluxerly method can still be called. The `client.rest.call` method sends it with the bot's token, and the compiler checks it against Fluxer's API description, with Fluxer's own field names. This one reads a channel's latest messages:
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function latestContents(client: Client, channelId: string) {
const result = await client.rest.call("GET /channels/{channel_id}/messages", {
params: { channel_id: channelId },
query: { limit: 10 },
})
return result.map((response) => response.body.map((message) => message.content))
}
```
The route is written as Fluxer's documentation writes it. The `params` field fills its path template, `query` holds the query and `body` the JSON body, and the response body has the route's type, so a misspelled field, a missing required field or an unlisted route fails to compile. An array sends a repeated parameter, so `query: { tag: ["101", "102"] }` sends `tag=101&tag=102`, and the message routes also take `files`
The types come from Fluxer's OpenAPI document at the commit this release pins, with a few reviewed corrections that cite Fluxer's source. [`RestRoutes`](https://fluxerly.neontechspace.com/docs/api/js-ts/rest-routes/) links each route to its section of Fluxer's documentation. Nothing checks Fluxer's answer at runtime, so check a response field before relying on it
### Routes newer than the SDK
The `client.rest.request` method takes any path and body, for a route or field newer than the pinned description, or a route the typed list leaves out, such as one that needs no token and is not among the public reads it types. This one reads the community guidelines link of Fluxer's message report flow, from such a route:
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function reportGuidelines(client: Client) {
const result = await client.rest.request<{ guidelines_url?: unknown }>({
method: "GET",
path: "/reports/flows/message",
})
return result.map((response) =>
typeof response.body.guidelines_url === "string" ? response.body.guidelines_url : undefined,
)
}
```
The path is the part after `/v1`, with the query in `query`. The type argument only names the expected body, so check each field before relying on it
### What both methods share
Both use the queue, rate limits, deadline and logging of the named methods. Logs name only the route, never the query, body or answer, unless `logging.unsafe` prints masked bodies for the `rest` category while debugging. A non-2xx answer fails the Result with `RestRequestError`, whose `status` and `apiError` say what Fluxer answered, and invalid input, such as a missing path parameter, fails with reason `input` before anything is sent. Neither method reads nor updates the caches
## Read an event without a type
Every gateway event also arrives as the `raw` event, in the form Fluxer sent it. Types listed in `gateway.ignoredEvents` do not arrive, apart from the mention and reaction batch exceptions that `gateway.ignoredEvents` describes. When `documented` is true, the SDK describes the event's type, and comparing `t` with that type gives `d` its described fields under Fluxer's own names, so a misspelled field fails to compile. The SDK builds those descriptions from Fluxer's documentation, with reviewed corrections from Fluxer's server code. This one reads the unread post counts Fluxer sends in `FORUM_UNREADS`:
```ts
import type { Client } from "@neontechspace/fluxerly"
export function watchForumUnreads(client: Client) {
return client.on("raw", (dispatch) => {
if (!dispatch.documented || dispatch.t !== "FORUM_UNREADS") return
console.log(`Forum ${dispatch.d.channel_id} reported ${dispatch.d.threads.length} posts`)
})
}
```
The types come from Fluxer's gateway and HTTP API documentation at the Fluxer commit the SDK was reviewed against, with those corrections. They check nothing at runtime: `d` is still the body Fluxer sent, which can lack a documented field or carry a newer one, so check a field before relying on it. A type the SDK does not describe, such as one Fluxer added later, still arrives, with `documented: false` and an unknown `d` to validate. `GatewayDispatchPayloads` names the payload of each documented type, and `GatewayPayloadObjects` the objects inside them, keyed by the address of their documentation, such as `GatewayPayloadObjects["/http-api/messages/#message-object"]`
A `raw` handler turns off [`ignoredEvents: "auto"`](https://fluxerly.neontechspace.com/docs/configuration.md#events-and-the-gateway), so the bot also receives the event types that setting would skip. With `ignoredEvents: "auto"`, register the `raw` handler before `client.connect`. Automatic filtering is decided when Identify starts a new session. Adding a `raw` handler later does not change that session's filtering, and Resume keeps the existing list
## Read a refused voice join
The `raw` event receives only opcode 0 dispatches. Fluxer sends an opcode 12 Gateway Error frame when it refuses a voice join the session asked for, and that frame arrives as the `gatewayError` event, with Fluxer's `code` and `message` in `d`:
```ts
import type { Client } from "@neontechspace/fluxerly"
export function reportRefusedVoiceJoins(client: Client) {
return client.on("gatewayError", (frame) => {
console.log(`Shard ${frame.shardId} could not join voice: ${frame.d.code}`)
})
}
```
At the reviewed Fluxer commit the gateway sends `VOICE_PERMISSION_DENIED`, `VOICE_MEMBER_TIMED_OUT`, `VOICE_CHANNEL_FULL`, `VOICE_CONNECTION_LIMIT_REACHED`, `VOICE_CAMERA_USER_LIMIT`, `VOICE_UNCLAIMED_ACCOUNT`, `VOICE_ACCOUNT_VERIFICATION_REQUIRED`, `VOICE_E2EE_REQUIRED`, `VOICE_P2P_CONSENT_REQUIRED`, `VOICE_P2P_UNAVAILABLE` and `VOICE_TOKEN_FAILED`, while other refused joins send no frame. The connection stays open. The frame has no sequence number, so Resume does not replay it and a frame sent while the shard is disconnected is lost. The `gateway.ignoredEvents` option never suppresses it. Without a `gatewayError` subscription, the SDK logs each frame at Warn with the code `gateway.gatewayError`. In a test, `test.emitGatewayError({ code, message })` delivers one to the bot
## Send a gateway command without a method
The `client.gateway.send` method sends an outgoing gateway command that has no dedicated method, such as opcode 28 (`REQUEST_FORUM_UNREADS`). [Core concepts](https://fluxerly.neontechspace.com/docs/core-concepts.md#gateway-and-rest) explains how it shares pacing with the SDK's own commands. For standard Voice State Update signaling (opcode 4), use [`client.voice`](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#voice) instead, which routes to the community's owning shard and keeps `gateway.ignoredEvents: "auto"` active. When Fluxer refuses a voice join sent through `client.voice` or a raw opcode 4 frame, the answer is a [Gateway Error frame](https://fluxerly.neontechspace.com/docs/raw-requests-and-events.md#read-a-refused-voice-join)
The Effect API has the same `client.rest.call`, `client.rest.request`, `client.gateway.send` and `client.voice` methods, and the same `raw` and `gatewayError` events
---
# Make bot operations reliable
Report failures, retry only when it is safe, set deadlines and handle uncertain writes
Most bots need little code for reliability. The SDK reconnects on its own, keeps running when a handler fails and reports callback failures with their full cause. A handler only has to return the Result of its reply, and retry only when the SDK confirms that retrying is safe
## Return the reply's Result
The default API returns expected failures, such as a missing permission or a network error, in a [`Result`](https://fluxerly.neontechspace.com/docs/glossary.md#result) instead of throwing. A handler that returns that Result hands a failure to the SDK
The SDK holds a `rest.rejected` Warn for an HTTP 401 or 403 rejection for up to one second. If the handler returns that same failure while the Warn is held and no `onError` hook is configured for it, only the handler's failure record appears. See [rejection logging](https://fluxerly.neontechspace.com/docs/logging.md#read-the-default-output)
```ts
import { setTimeout as wait } from "node:timers/promises"
import { errors, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
events: {
messageCreate: async ({ message, reply, signal }) => {
if (message.content !== "!ping") return undefined
const first = await reply("Pong!")
if (first.isOk() || !errors.isRetryable(first.error)) return first
// The signal ends the wait when the bot stops
await wait(errors.retryAfterMs(first.error) ?? 1_000, undefined, { signal })
return reply("Pong!")
},
},
})
```
A successful reply returns its Result and nothing else happens. A failed reply is sent again only when `errors.isRetryable` confirms that the first attempt did not post a message, so the bot never answers twice. Any remaining failure is returned, and the SDK reports it to `onError` or logs it at Error with its message and suggested fix
Either return a failed Result or handle it in the handler, not both. A handler that logs a failure and then returns it reports the same failure twice
The bot itself follows the same rule. When a failure stops it, such as a rejected token, `runBot` logs that failure once and sets `process.exitCode` to 1, so the top-level code needs no error handling
## Report failures that have no Result
Some failures have no caller to return to: A throwing event handler or one that returns an Err, a failed command, a failing [collector](https://fluxerly.neontechspace.com/docs/glossary.md#collector) callback or filter, a message cache callback that throws or a subscription closed by a full queue with `overflow: "stop"`
The SDK sends each of them to the client's `onError` option with the original error and the IDs of the message involved. The SDK adds no message content itself, though application errors can still contain some. Without a hook it logs them at Error with the full message, stack and cause chain
```ts
import { createClient, type FailureReport } from "@neontechspace/fluxerly"
export function createReportedClient(token: string, track: (report: FailureReport) => Promise) {
return createClient({ token, onError: (report) => track(report) })
}
```
The `report.describe()` method returns readable plain text for an error tracker or a chat alert, and `report.describe({ color: "auto" })` adds terminal styling, icons and gutter rails only when standard error is an interactive terminal and color is not disabled by `NO_COLOR`, `FORCE_COLOR=0` or `TERM=dumb`. A failing hook is logged together with the original failure and never retried
How reports are queued
Reports reach the hook one at a time in order. Up to 256 wait while the hook is busy.
Later reports are logged instead and counted in `diagnostics().counters.reportsDropped`, so none disappear silently.
Shutdown does not wait for a hook that never finishes
## Read an SDK error
Every SDK error extends `FluxerlyError` with a stable `code`, an optional fix `hint`, safe `details` and a standard `cause`:
- Readable text: The `describeError(error)` function prints the code, hint, safe details, retry guidance, Fluxer field validation issues and cause chain. Pass `{ color: "auto" }` to style output only when standard error is an interactive terminal and color is not disabled by `NO_COLOR`, `FORCE_COLOR=0` or `TERM=dumb`
- Safe retries: The `errors.isRetryable(error)` function says whether repeating the same call is safe. For an Effect `Cause` it is true only when the `Cause` has at least one reason and every reason is a retryable failure, so a defect, an interruption or an empty `Cause` gives false
- Required wait: The `errors.retryAfterMs(error)` function returns the wait in milliseconds that Fluxer or the SDK requires before a retry, or `undefined` when the error carries none. For a `Cause` it returns the longest wait among its failures
- Fluxer's reason: The `errors.apiCode(error)` function returns Fluxer's error code name, such as `"missingPermissions"`, or `undefined`. When Fluxer rejects individual fields, `error.apiError?.validationErrors` lists each `{ path, providerCode, explanation }` entry
- Request reach: The `errors.outcome(error)` function returns `"notDispatched"`, `"rejected"` or `"unknown"`, or `undefined` when the SDK cannot establish it, such as for cancellation. Only `"notDispatched"` shows that a write was not sent, so treat any other value, including `undefined`, as a write that may have applied and check remote state before repeating it
- Missing resource: The `errors.isNotFound(error, "member")` function is true for an HTTP 404, and with a resource name (including `"ban"` for `UNKNOWN_BAN`) only when Fluxer named that resource as the missing one. A 404 does not say why, because Fluxer answers `UNKNOWN_CHANNEL` for a missing channel and also for message and reaction requests in a thread from a bot that is no longer in the community, while other requests from such a bot get a 403 `missingPermissions`
- Missing permissions: For `"missingPermissions"`, `error.details.requiredPermissions` lists the permissions Fluxer checks for the failed operation, such as `ViewChannel` and `SendMessages`, when the SDK knows them
- Branching: The `errors.match(error, handlers)` function calls the handler named by the error's `_tag`
An unexpected SDK or cleanup failure is not an Err. It rejects the Promise with `SdkDefect`, whose `reasons` list every failure and whose `cause` is the first defect, or the first failure when there is no defect. In the example above, `await runBot(...)` lets it end the process with Node.js's error output and a failing exit code. An application with its own top-level `try`/`catch` can alert, restart or print `describeError(error)` there instead
## Set a request deadline and allow cancellation
Every request has a 30-second deadline by default. For REST calls, the client option `rest.defaultTimeoutMs` changes that default, while gateway count and member-chunk requests keep their own 30-second default. Pass `timeoutMs` to set the deadline of one call, and a `signal` to stop waiting when the caller cancels. Create an `AbortController` for that task and pass its `signal` to this helper
```ts
import type { Client, MessageReference } from "@neontechspace/fluxerly"
export async function fetchUntilCancelled(
client: Client,
message: MessageReference,
signal: AbortSignal,
) {
return await client.messages.fetch(message, {
signal,
timeoutMs: 5_000,
})
}
```
The Result contains the message or a typed error. Aborting the signal produces `CancelledError`, and the five-second deadline also stops the request. Both wait for SDK cleanup before the Result arrives. A provider can still complete work it already received, so keep the controller with the operation that owns the user request
Handlers in `runBot` receive a `signal` that is aborted when the bot stops. The bound `reply` already uses it
## Send once when the outcome is uncertain
A lost response, timeout or cancellation after a message was sent can leave it posted. Such a failure is an [uncertain write](https://fluxerly.neontechspace.com/docs/glossary.md#uncertain-write), and `errors.isRetryable` returns false for it. Do not send again just because the result is uncertain. Supply an application operation ID as the message nonce, and reconcile through an application workflow before deciding what to do next
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function sendOnceAndDiagnose(
client: Client,
channelId: string,
content: string,
operationId: string,
) {
const sent = await client.messages.send(
channelId,
{ content, nonce: operationId },
{ timeoutMs: 5_000 },
)
const diagnostics = client.diagnostics()
console.info("Fluxerly client capacity", {
state: diagnostics.state,
activeRequests: diagnostics.rest.activeRequests,
queuedRequests: diagnostics.rest.queuedRequests,
retainedMessages: diagnostics.caches.messages.retainedEntries,
})
return sent
}
```
The helper makes one send call, returns its `Result`, and logs only local state, request counts and cache counts from [`diagnostics`](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#diagnostics). A nonce has best-effort duplicate suppression for a limited window, not durable idempotency or exactly-once delivery
## Start, recover and stop the connection in one function
Without `runBot`, use `client.run` when one signal should control startup, recovery and shutdown. Pass a disconnected client with its handlers already registered and an `AbortSignal` controlled by the application
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function runUntilStopped(client: Client, signal: AbortSignal) {
return await client.run({ signal })
}
```
Once `run()` starts, it waits through connection startup and recovery. It finishes after a normal stop, permanent failure or cancellation, once SDK cleanup is done
The [`run`](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#run) method requires a disconnected client and closes it permanently once the accepted run ends. Alternatively, use `connect` for startup, `waitForClose` for later terminal failure and `shutdown` for final cleanup. Aborting `waitForClose` alone does not stop the client
## Limits and retry rules
The SDK applies these rules automatically. They need no configuration, but explain behavior seen in logs and diagnostics
Automatic request retries
A GET request, or a call to `threads.fetchPostData`, that fails with a network error or HTTP 500, 502, 503 or 504 is retried at most twice. A connection lost while the response body arrives counts as a network error.
A write is sent again only after Fluxer confirms a rate limit with HTTP 429, so a write with an unknown outcome is never repeated automatically.
Each retry after a network error or HTTP 500, 502, 503 or 504 is counted in `diagnostics().counters.restRetries` and logged as `rest.retry` at Debug. A resend after HTTP 429 is counted in `rateLimitWaits` instead, as described under Rate limits
Rate limits
The SDK waits for [rate limits](https://fluxerly.neontechspace.com/docs/glossary.md#rate-limit) on its own when the request body can be sent again, and logs waits of one second or more at Warn. A webhook or inline upload with a Blob, File or stream attachment fails with reason `rateLimit` instead and logs `ratelimit.notResent` at Warn. If the upload read the stream, `errors.isRetryable` returns false. Send again with a new stream or with the file as bytes. If the upload never read the stream, as when a rate-limit pause outlasts the deadline before sending, `errors.isRetryable` returns true and the same stream can be used again. Waiting counts toward each operation's deadline. A wait that would pass the deadline fails at once with `ratelimit.deadline`, including for an operation queued behind an earlier pause, and the error's `retryAfterMs` names the remaining wait
A global HTTP 429 pauses unrelated API routes on the same client, including when a valid global header accompanies an unreadable error body. Cancelling one queued operation does not clear the shared pause
An HTTP 429 that does not identify its limit also pauses every API request of the client for its wait. Such a response has no `X-RateLimit-Bucket` or `X-RateLimit-Scope` header and no JSON body with a boolean `global` member, as when a proxy in front of the API answers. Fluxer did not declare it global, so its records say `global: false` with `pause: "client"`, and other processes of a supervisor keep running. A limit Fluxer identifies as a route limit pauses only its bucket. When the `Retry-After` header and the body's `retry_after` disagree, the SDK waits for the longer one. After such a pause, one request goes first and the others wait for its answer. If that request meets another unidentified 429, the next pause doubles the wait it asks for, up to a minute, plus a little jitter, so a longer outage does not wake the whole queue every few seconds
Server-provided bucket identifiers refine request grouping automatically, so bot code does not configure rate-limit groups. Matching limits share a wait, while independently limited resources stay separate. The first requests can still receive a 429 before the grouping is learned. The [client contract](https://fluxerly.neontechspace.com/docs/api/js-ts/client/) explains scope metadata and retry boundaries
When rate limits hold queued requests for a second, the client logs one `ratelimit.queueHeld` record that says how many requests wait, why and for how long. A global limit or a client pause after an unidentified 429 is a Warn. Used-up route limits are a Debug that names the route with the most waiting requests, because they are part of ordinary pacing. Each reason is logged at most once a minute. The `diagnostics().rest.rateLimitHold` field shows the same summary at any moment, or null when no queued request waits for a rate limit
Request queue and capacity
By default, a client runs up to 4 API requests at a time per local shard, capped at 64 for the client, and lets 256 requests wait. An explicit `rest.concurrency` stays fixed instead of scaling with the shard count. A request that finds the queue full fails at once with reason `busy` and was never sent, so it is safe to retry later.
The `rest` client option changes these limits, as described in [configuration](https://fluxerly.neontechspace.com/docs/configuration.md#connection-and-requests)
Rejected gateway messages
Gateway receive protection is automatic. A message beyond the fixed receive ceiling, or invalid UTF-8, stops the connection rather than repeatedly reconnecting to the same rejected data. A known event that fails validation is skipped instead: The SDK logs `gateway.dispatchRejected` at Warn with the event type and failing field, clears cache entries it could have changed and keeps the session running
Set `gateway: { onMalformedDispatch: "terminate" }` to end the client instead. The [client contract](https://fluxerly.neontechspace.com/docs/api/js-ts/client/) documents the ceiling and failure codes. Subscription queue limits apply separately and do not bound JSON parsing memory
Reconnects
After a lost connection the SDK resumes the session when Fluxer allows it and otherwise starts a new one, waiting a growing random delay between attempts.
The default recovery keeps retrying transient failures. A permanent failure, such as a rejected token, ends the run with a connection error.
The `connection.recovery` option changes the delays, as listed in [`ConnectionRecoveryOptions`](https://fluxerly.neontechspace.com/docs/api/js-ts/options/#connectionrecoveryoptions)
---
# Shard and supervise a bot
Split a large bot across gateway connections and processes, and resume sessions after a restart
A [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard) is one [gateway](https://fluxerly.neontechspace.com/docs/glossary.md#gateway) connection that carries the events of part of the bot's communities, which Fluxer's API calls [guilds](https://fluxerly.neontechspace.com/docs/glossary.md#guild). A bot starts with one connection, which is enough for about 2,000 communities. Fluxer allows at most 2,500 communities per shard and refuses to start a new session, the gateway login of one shard, above that with close code 4011 (sharding required)
## Let the SDK choose the shard count
Set `sharding: "auto"` and keep everything else the same. At the first connect, the SDK counts the bot's communities and opens one shard for every 2,000, all in this process. The lower target leaves room below Fluxer's ceiling, because communities do not split evenly across shards
```ts
import { runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
sharding: "auto",
events: {
messageCreate: ({ message, reply }) => {
if (message.content !== "!ping") return undefined
return reply("Pong!")
},
},
})
```
Handlers and commands work the same on every shard. The `client.shards` list shows the shards this client owns, and a handler registered with `client.on` receives an `EventContext` third argument whose `shardId` names the shard that delivered the event
A `runBot` handler finds the same object in its `context` field. Fluxer checks a shard's community count when it starts a new session, not while it runs. When Fluxer refuses a session with close code 4011, the SDK moves every shard to a larger plan in the same process, so the bot keeps running
A bot without `sharding` settings makes the same move from its one shard when Fluxer refuses it with 4011, so it keeps running too. Until it sets `sharding: "auto"`, each start first opens a session that Fluxer refuses before the move. An explicit `totalShards`, including 1, never moves
Each `client.shards` entry has a `sessionEpoch` number, which stays the same across a Resume and changes whenever that shard starts a new session, including after a move. A changed value means the shard's events in between may have been missed, and Fluxer then sends each of its communities again through `guildCreate`, so state kept from events can be rebuilt there
The `EventContext` also carries `sessionEpoch`, fixed when the client accepted the event, so an event still waiting in a handler's queue keeps its own session. Compare `context.sessionEpoch` rather than the shard's current value, and keep the last value seen per community, since one shard serves many communities
Details of automatic sizing
The count pages through the bot's community list under its own deadline, as long as `connection.startupTimeoutMs`, and supports 1 through 16,384 shards. The shards then start one second apart, and the startup deadline grows by one second for each shard after the first
Until the count completes, `client.shards` and `diagnostics().shards` are empty. A failed count fails startup like a connection failure, and a page that does not move past the previous one fails it at once with a `ConnectionError` instead of waiting for the deadline
When Fluxer closes a shard with 4011 while the client runs, the SDK counts again and moves every shard to the plan for the new count, or to one more shard when the count still fits the old plan. Every shard then starts a new session, so events sent during the move are missed, and the community caches fill again from the new sessions
The move is logged once at Warn with code `lifecycle.resharded` and the old and new totals. After 3 moves within an hour, or at 16,384 shards, the next 4011 closure ends the client with a `ConnectionError`, as it does for an explicit `totalShards`
Automatic sizing suits one process that owns every shard. Processes that split shards between them need an explicit total, unless the [supervisor](https://fluxerly.neontechspace.com/docs/sharding.md#run-shards-in-several-processes) sizes the plan for them
## Command pacing across reconnects
Outgoing presence, member requests, counts and `gateway.send` commands share a rolling send budget on each shard. A Resume within the same running client retains that send history, so reconnecting does not allow a second burst in the same window. A fresh Identify starts a new session and clears the history. Heartbeats, Identify and Resume bypass ordinary command pacing
Waiting custom commands fail when the connection is lost and are not replayed. Retained presence intent is published on the next ready connection using its latest value. Send history is kept in memory only and is not part of a saved session snapshot
## Resume after a restart
A restarted bot normally starts new sessions and misses the events sent while it was down. Fluxer keeps a disconnected session for 60 seconds. A session store saves each connected shard's session at shutdown and offers it at the next startup, so a quick restart, such as a deploy, can resume and receive the missed events within Fluxer's replay limits
```ts
import { fileSessionStore, runBot } from "@neontechspace/fluxerly"
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
sharding: { totalShards: "auto", sessions: fileSessionStore("sessions") },
events: {
messageCreate: ({ message, reply }) => {
if (message.content !== "!ping") return undefined
return reply("Pong!")
},
},
})
```
The `fileSessionStore` function keeps each shard's snapshot in its own file in the given folder, relative to the current working directory, and replaces a file only once its new contents are fully written. A snapshot contains the session ID, which lets the token resume the session, so keep the folder out of version control and readable only by the bot's account
Separate processes need separate folders unless their shard IDs never overlap. The store works with one shard as well: Pass `{ totalShards: 1, sessions: fileSessionStore("sessions") }`. To keep snapshots elsewhere, such as in a database, pass an object with `load` and `save` methods instead, as the [`SessionStore`](https://fluxerly.neontechspace.com/docs/api/js-ts/sharding-and-supervision/#sessionstore) reference describes
When a saved session is not used
Resumable snapshots are saved only during a clean shutdown, after each socket has closed. Before a shard resumes a snapshot, it marks the stored one as used, so a crash leaves no resumable snapshot and the same snapshot is never resumed twice. A snapshot older than 60 seconds, a malformed or used one, or one for another gateway address is ignored and logged at Warn
A failed `load` or `save`, or one that takes longer than 5 seconds, is logged in full at Error. In every case the shard starts a new session, so a store problem never stops the bot. If Fluxer no longer holds the session, the resume fails and the shard starts a new session as it would after any lost connection
If only part of the saved session's replay arrived first, the shard clears those cached community observations and their dependent resources before starting the new session. Reads cached during that wait are cleared again at READY. A successful resume retains the replayed observations
Resume replays most missed dispatches but sends no fresh community snapshot. Once every shard is ready, the SDK refills the enabled community, role and channel caches through REST, one request at a time, and logs `lifecycle.cacheRefill`. Set `sharding.refillCaches` to `false` to keep only observations from replay, later events and requests
## Choose the shards explicitly
A fixed plan splits shards between processes or hosts. Each process uses the same `totalShards` and its own non-overlapping `shardIds`
```ts
import { runBot } from "@neontechspace/fluxerly"
const shardIds = (process.env.SHARD_IDS ?? "0,1").split(",").map(Number)
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
sharding: { totalShards: 4, shardIds },
events: {
messageCreate: ({ message, reply }) => {
if (message.content !== "!ping") return undefined
return reply("Pong!")
},
},
})
```
Start this file twice, once with `SHARD_IDS=0,1` and once with `SHARD_IDS=2,3`. Shard 0 also receives direct messages, so only the process that owns it sees them. Omit `shardIds` to own every shard in one process
To find the process that owns a community, pass its guild ID and the total to `snowflakes.shardFor(guildId, totalShards)`, which returns the shard Fluxer routes it to. Inside a process, `client.shardIdForGuild(guildId)` returns the local shard for that community, or `undefined` when another process owns it
Coordinate new sessions across processes
Fluxer limits how quickly a bot may start or resume sessions: 300 Identify and Resume commands together per IP address in each 60 seconds. One client spaces its own shards' Identify commands by one second, but not its Resume commands, and separate processes do not know about each other
Pass `sharding.identify` with a `permit(shardId, totalShards, signal)` function, backed for example by a shared lock service, to make every process wait for its turn. The SDK calls it before each new session, never before a resume. Resumes still count toward Fluxer's limit, so leave room for them when spacing permits. The SDK sends Identify as soon as the permit resolves. The coordinator then owns the pacing, so it should space its permits
Other gateway limits are shared by every client on one source IP address. Each Fluxer gateway node allows 256 open connections and 6,000 client payloads in each fixed 60-second window, counting heartbeats, session commands and traffic from other bots on that address. The SDK paces application commands per session, so many busy shards on one address can reach the payload limit together. Fluxer closes such a connection with code 4008. When a close with that code repeats, spread shards across outbound addresses or lower their combined traffic before adding more workers
A rejected permit is logged at Error and retried like a connection failure. The [`IdentifyCoordinator`](https://fluxerly.neontechspace.com/docs/api/js-ts/sharding-and-supervision/#identifycoordinator) reference describes the timing. Children of the [supervisor](https://fluxerly.neontechspace.com/docs/sharding.md#run-shards-in-several-processes) below are paced by their parent and cannot set `sharding.identify`. To share the budget with other hosts, pass the same coordinator to the supervisor's `identify.coordinator` option, and the parent asks it before each child's new session
## Run shards in several processes
The [supervisor](https://fluxerly.neontechspace.com/docs/glossary.md#supervisor) starts several Node.js child processes, gives each its shards, restarts children that crash and stops them all on shutdown. Use it when one process is not enough, for example to spread a large bot over several CPU cores. One process can already own several shards, so smaller bots do not need it
Save the parent as `supervisor.js`. With `totalShards: "auto"` it counts the bot's communities at start, as `sharding: "auto"` does, and splits the shards evenly across up to `processes` children, with at least one shard per child. The count needs the bot token in the parent too
```ts
import { describeError, supervisor } from "@neontechspace/fluxerly"
const workers = supervisor.create({
entry: new URL("./shard-worker.js", import.meta.url),
token: process.env.FLUXER_BOT_TOKEN,
totalShards: "auto",
processes: 2,
})
const stop = () => {
workers.shutdown().then(undefined, (defect: unknown) => {
console.error(describeError(defect))
process.exitCode = 1
})
}
process.once("SIGINT", stop)
process.once("SIGTERM", stop)
const started = await workers.start()
const closed = started.isOk() ? await workers.waitForClose() : started
process.removeListener("SIGINT", stop)
process.removeListener("SIGTERM", stop)
if (closed.isErr()) {
console.error(describeError(closed.error))
process.exitCode = 1
}
```
The supervisor, unlike `runBot`, does not set the exit status, so the parent sets `process.exitCode` itself when the supervisor fails
Save each child as `shard-worker.js`. It creates its client through `supervisor.child.run`, registers the bot's commands and handlers in `configure`, and runs until the parent stops it. It sets a failing exit status too, so the parent can see that the child crashed
```ts
import { commands, describeError, supervisor } from "@neontechspace/fluxerly"
const result = await supervisor.child.run({
token: process.env.FLUXER_BOT_TOKEN,
configure: ({ client }) => {
commands
.create({ prefix: "!" })
.registerMany({
ping: { execute: ({ reply }) => reply("Pong!") },
})
.attach(client)
},
})
if (result.isErr()) {
console.error(describeError(result.error))
process.exitCode = 1
}
```
Start the parent with `node --env-file=.env supervisor.js`. Children inherit its environment and Node.js flags, so they read the same token. With TypeScript, point `entry` at `shard-worker.ts`
The supervisor installs no signal handlers of its own, which is why the parent handles SIGINT and SIGTERM and calls `shutdown()`. That asks every child to stop, waits for them to exit and force-terminates a child that takes longer than 5 seconds
In both APIs, a child stopped by the parent first lets running handlers, queued handler events, running scheduled tasks and REST requests finish for up to 4 seconds, one second less than `shutdownTimeoutMs`. The same drain applies to children stopped while an automatic plan grows
A child stopped by its own failure or a lost parent message channel cancels running work without draining. Each child's output appears in the parent's output with a `[shard N]` or `[child id]` label, and the parent logs child starts, exits, crashes and restarts. Under systemd, add `KillMode=mixed` as described in [deploying](https://fluxerly.neontechspace.com/docs/deploying.md)
A successful `start()` means every child accepted its shards and finished `configure`, not that every gateway session is ready. Use `workers.waitForReady()` to wait for connected sessions and `workers.status()` for a snapshot of each child. The Effect entry point exports a `supervisor` with the same options
Unknown keys in supervisor creation, assignment, restart, Identify and child-run options fail with `ConfigurationError`, with a suggested name when one is close. Child-run options are checked before waiting for the parent. The default API also checks the options passed to `waitForReady`, which accepts only `signal`. The Effect wait is cancelled by interruption instead
To resume sessions across a deploy, give each child the [session store](https://fluxerly.neontechspace.com/docs/sharding.md#resume-after-a-restart) from above through `clientOptions: { sharding: { sessions } }` in `supervisor.child.run`. The parent still assigns the shards, so `sessions` and [`refillCaches`](https://fluxerly.neontechspace.com/docs/sharding.md#resume-after-a-restart) are the only sharding settings a child accepts
Some of Fluxer's limits apply to the whole bot account rather than to one process, so the children share them through the parent:
- When Fluxer pauses every request of the account with a global rate limit, the child that learns of it tells the parent, and the parent holds the other children's REST requests until the same time. A request that cannot wait that long fails at once with reason `rateLimit` and `retryAfterMs`
- Fluxer accepts 12 member requests per account in 10 seconds and drops the rest without an answer. Each child asks the parent before `members.iterateChunks` sends a request, and the parent allows at most 12 in any 11 seconds across all children. A request past that fails at once with reason `rateLimit` and `retryAfterMs`. A member request sent with `gateway.send` counts too but is never refused
A child that gets no answer from the parent within one second counts only its own member requests and logs `supervisor.memberRequestsLocal` once. Per-route rate limits stay with each child, and processes outside this supervisor that use the same token are not counted
Shard plans and assignments
A numeric `totalShards` fixes the total. Use `processes` for a number of children, `shardsPerProcess` for a number of shards per child, or `assignments` to name each child and its shards, such as `[{ id: "a", shardIds: [0, 1] }, { id: "b", shardIds: [2, 3] }]`
Children created by `processes` or `shardsPerProcess` are named `process-0`, `process-1` and so on, and each owns a contiguous block of shards. An automatic plan is counted at `start()`, and restarts keep it. A failed count fails `start()` with `SupervisorError` reason `shardCount`
With `totalShards: "auto"`, a child's close code 4011 makes the supervisor stop every child, count again and start children for a larger plan, logging a `supervisor.resharded` record. A numeric total stays fixed and follows the restart policy. After 3 such moves within an hour the supervisor fails instead. With `totalShards: "auto"`, the `instance` and `transport` options select the Fluxer instance and HTTP implementation for the count, as they do for a client
Restart limits and timeouts
A child that exits unexpectedly is replaced by default, up to `maxAttempts` times in a row (default 3), with a delay that starts at `minDelayMs` (default 1 second) and doubles up to `maxDelayMs` (default 30 seconds). Adjust them with `restart: { maxAttempts: 5 }`, for example
A child that ran for `healthyResetMs` (default 60 seconds) after finishing `configure` gets its full budget and the first delay back, so only a crash loop uses up the attempts. When a child uses up its attempts, the supervisor fails and stops the other children. With `restart: false`, the first unexpected exit does the same
Each child has `startupTimeoutMs` (default 30 seconds) to accept its assignment and finish `configure`, and `shutdownTimeoutMs` (default 5 seconds) to exit after a stop request. The parent logs why before it acts: `supervisor.startupTimeout` when a child misses its startup time, `supervisor.terminated` before it force-terminates a child and `supervisor.identifyUnacknowledged` when a child does not confirm a session start, which stops that child
The parent's Identify queue counts against each child's `connection.startupTimeoutMs`. With many shards, set it in `clientOptions` to at least 55,000 ms, which covers Fluxer's 25-second session start, plus the total shard count times `identify.minimumSpacingMs`. The supervisor's `startupTimeoutMs` covers configuration and automatic shard counting, not gateway readiness
When reading a child's output fails, `supervisor.outputFailed` records the error and that stream is no longer forwarded. A replacement is a new process with a new client. A crash leaves no resumable session, so the replacement starts new sessions. The [`SupervisorOptions`](https://fluxerly.neontechspace.com/docs/api/js-ts/sharding-and-supervision/#supervisoroptions) reference lists every setting, including `childOutput`, `childEnvironment` and `execArgv`
## Watch the bot's health
A connected shard can still have a stopped subscription. The [application supervision guide](https://fluxerly.neontechspace.com/docs/application-supervision.md) shows how to watch the connection and a critical subscription together, and how to decide between failing and restarting. Across processes, `workers.status()` reports each child's process state, its latest connection state and its latest `diagnostics`: The child client's gateway latency, shard states, REST queue, cache use and counters, sent every 5 seconds by default (`diagnosticsIntervalMs`). The `restart` option replaces a child process that exits
---
# Build a small bot
Combine commands, arguments, embeds, events, guards, cooldowns and shutdown in one file
This bot fits in one file and combines what most bots need: Commands with an argument, a help command, an embed, a welcome message for new members, a permission check, a cooldown, error reporting and a clean stop. It builds on the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md), so start there if the SDK is not installed yet
## The complete bot
Save this as `bot.js`, or `bot.ts` for TypeScript, in the quick start's folder. Like the JavaScript and TypeScript quick start bots, it exports its options as `bot`, so the test that `fluxerly init` writes for those starters still runs it. A project from `--template effect` needs [the Effect version](https://fluxerly.neontechspace.com/docs/small-bot.md#the-effect-version) instead, saved as `bot.ts`:
```ts
import { builders, defineBot, describeError, format, guards, runBot } from "@neontechspace/fluxerly"
// Optional channel that receives welcome messages
const welcomeChannelId = process.env.WELCOME_CHANNEL_ID
export const bot = defineBot({
// Handler and command failures arrive here instead of stopping the bot
onError: (report) => {
const source = report.command ? `Command ${report.command}` : `Handler ${report.event ?? report.kind}`
console.error(`${source} failed:\n${describeError(report.error)}`)
},
setup: () => {
if (!welcomeChannelId) console.info("WELCOME_CHANNEL_ID is not set, so the bot sends no welcome messages")
},
events: {
guildMemberAdd: async ({ event: member, client, signal }) => {
if (!welcomeChannelId || member.isBot) return
const channel = await client.channels.fetch(welcomeChannelId, { signal })
// A returned Err is reported to onError like a thrown error
if (channel.isErr()) return channel
if (channel.value.guildId !== member.guildId) return
return client.messages.send(
welcomeChannelId,
{
content: `Welcome, ${format.userMention(member.userId)}!`,
allowedMentions: { users: [member.userId] },
},
{ signal },
)
},
},
commands: {
prefix: "!",
commands: {
help: {
description: "List the commands",
// The first page holds up to 2,000 characters, enough for this bot's commands
execute: ({ help, reply }) => reply(help()[0] ?? "No commands"),
},
ping: {
description: "Check that the bot is online",
execute: ({ reply }) => reply("Pong!"),
},
greet: {
description: "Greet someone by name",
arguments: { name: { type: "text", rest: true } },
cooldown: { durationMs: 5_000, per: "user" },
execute: ({ values, reply }) => reply(`Hello, ${values.name}!`),
},
announce: {
description: "Post an announcement card",
arguments: { text: { type: "text", rest: true } },
guard: guards.requirePermissions(["ManageMessages"]),
execute: ({ message, values, reply }) => {
const card = builders
.embed()
.title("Announcement")
.description(values.text)
.color("#3b82f6")
.footer({ text: `Posted by ${message.author.username}` })
return reply({ embeds: [card] })
},
},
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main) await runBot({ token: process.env.FLUXER_BOT_TOKEN, ...bot })
```
## Run it
Start the bot with the `.env` file from the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md), or with the project's start script:
```sh
node --env-file=.env bot.js
```
For welcome messages, add the ID of the channel that should receive them to `.env`. A channel's ID is the last number in its link, which has the form `https://fluxer.com/channels//`:
```text
FLUXER_BOT_TOKEN=paste-the-token-here
WELCOME_CHANNEL_ID=paste-the-channel-id-here
```
Without `WELCOME_CHANNEL_ID`, the bot prints a note at startup and runs everything else. Then try it in a channel the bot can read and reply to:
- Send `!help` to list the commands
- Send `!ping` to get **Pong!**
- Send `!greet Ada Lovelace` to get **Hello, Ada Lovelace!**
- Send `!greet` alone to see what is missing and how to use the command
- Send `!announce Movie night on Friday` to post an announcement card. Only members who can manage messages may use it
- A new member joining the community gets a welcome message in the configured channel
Press Ctrl+C to stop the bot
## How it works
As in the quick start, `defineBot` holds the bot's options: The handlers, the commands and the settings. The last line passes them to `runBot` together with the token, which connects and runs until the bot stops. That line runs only when Node.js runs the file, so a test can import `bot` and pass it to `createTestBot` instead, as [Testing a bot](https://fluxerly.neontechspace.com/docs/testing.md) shows
### Commands
The `commands` option of `runBot` turns messages that start with the prefix `!` into commands. Each key of the inner `commands` object is a command name, and `description` feeds generated help. The `reply` function answers the message that ran the command, and it accepts a plain string
Each command returns the result of its reply. If the reply fails, the SDK reports that failure to `onError`, the [error hook](https://fluxerly.neontechspace.com/docs/small-bot.md#error-reporting) described below, like a thrown error. The [commands guide](https://fluxerly.neontechspace.com/docs/commands.md) covers aliases, groups, help pages and more argument types
### Generated help
The `help` command calls `help()` from its context, which lists every command with its `description` and usage. It returns pages of at most 2,000 characters, so each page fits in one message, and this bot needs only the first one
### A typed argument
The `greet` command declares one argument, `name`, as text. With `rest: true`, it takes everything after the command name, so a name can contain spaces. The router converts the argument before `execute` runs, and in TypeScript `values.name` is a string
A command used wrongly gets a short explanation, such as `Missing name. Usage: !greet `. The `runBot` function answers rejected commands this way by default, and `onReject: "silent"` turns the answers off
Mentions in a reply do not notify anyone unless the message allows it, so `!greet @everyone` notifies nobody
### A cooldown
The `cooldown` setting lets each user run `greet` once every 5 seconds. A second attempt within that time is rejected, and the bot says once how long to wait. Use `per: "channel"` or `per: "guild"` to share the limit across a channel or a whole community
The router keeps cooldowns in memory, so they reset when the bot restarts. The [commands guide](https://fluxerly.neontechspace.com/docs/commands.md) explains how to share [cooldowns](https://fluxerly.neontechspace.com/docs/glossary.md#cooldown) between processes
### A permission guard
A [guard](https://fluxerly.neontechspace.com/docs/glossary.md#guard) decides whether a command may run. The `announce` command uses `guards.requirePermissions(["ManageMessages"])`, which allows it only for members who have the `ManageMessages` permission in that channel. It checks the person who sent the command, not the bot, and it denies the command in direct messages
The guard looks up the community, member, roles and channel, reading them from Fluxer when they are not cached. A denied member gets a reply such as `Using this command requires these permissions: Manage messages`, at most once every 5 seconds. The [communities and permissions guide](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md) explains how permissions are calculated
### An embed reply
An embed is a formatted card with a title, text, color and footer. The `builders.embed()` chain sets its parts, and the finished builder goes into the `embeds` list of a reply. Building sends nothing, and limits such as the title length are checked when the message is sent
The bot needs the `EmbedLinks` permission in the channel, which new communities grant to everyone. Without it, Fluxer rejects the whole reply, and the failure reaches `onError`. The [messages guide](https://fluxerly.neontechspace.com/docs/messages.md) shows more message options
### A welcome message
The `events` option registers a handler for each event name. The `guildMemberAdd` event arrives when someone joins a community the bot is in, and its handler receives the member as `event`, the `client` and a cancellation `signal`
The handler skips bots. It then reads the welcome channel with `client.channels.fetch`. Like every request, it returns a [Result](https://fluxerly.neontechspace.com/docs/core-concepts.md#results): Either a success, whose `value` holds the channel, or a failure, whose `error` says what went wrong, and `isErr()` tells them apart
The handler uses the channel to check that it belongs to the community the member joined, so a bot in several communities never announces one community's members in another. Passing `signal` lets the SDK cancel these requests when the bot stops
The mention in the welcome text notifies the new member because `allowedMentions` lists them. If the channel read fails, the handler returns the failed Result, which the SDK reports to `onError`
### Error reporting
The `onError` function receives every failure that has no caller to return it to: A failed command, event handler or reply. The report names the command or event, and `describeError` prints the full error with its code, hint and causes, with recognized credentials masked. The bot keeps running after a failure. Without `onError`, the SDK logs each failure itself
The [logging guide](https://fluxerly.neontechspace.com/docs/logging.md) shows how to change what the SDK prints
### Clean shutdown
By default, Ctrl+C or a stop request from a process manager stops the bot. The SDK gives running work up to 5 seconds to finish, cancels the rest, closes the connection and finishes its cleanup, and then `runBot` returns
When the bot could not connect or stopped for another reason, `runBot` logs that failure once and sets the process exit code to 1, so a shell or process manager sees a failed run. A missing token is reported the same way before the bot connects, and other invalid settings throw an error at once. The [reliability guide](https://fluxerly.neontechspace.com/docs/reliability.md) covers what happens between start and stop
## The Effect version
The same bot with the [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect) API returns an Effect from each handler and command. A failed channel read fails the handler's Effect, which the SDK reports to `onError`. With `processSignals: true`, Ctrl+C completes the program successfully. A failure that stops the bot is logged and sets a failing exit code, as with the default API
```ts
import { Effect } from "effect"
import { builders, defineBot, describeError, format, guards, runBot } from "@neontechspace/fluxerly/effect"
// Optional channel that receives welcome messages
const welcomeChannelId = process.env.WELCOME_CHANNEL_ID
export const bot = defineBot({
// Handler and command failures arrive here instead of stopping the bot
onError: (report) => {
const source = report.command ? `Command ${report.command}` : `Handler ${report.event ?? report.kind}`
return Effect.logError(`${source} failed:\n${describeError(report.error)}`)
},
setup: () =>
welcomeChannelId
? Effect.void
: Effect.logInfo("WELCOME_CHANNEL_ID is not set, so the bot sends no welcome messages"),
events: {
guildMemberAdd: ({ event: member, client }) =>
Effect.gen(function* () {
if (!welcomeChannelId || member.isBot) return
const channel = yield* client.channels.fetch(welcomeChannelId)
if (channel.guildId !== member.guildId) return
yield* client.messages.send(welcomeChannelId, {
content: `Welcome, ${format.userMention(member.userId)}!`,
allowedMentions: { users: [member.userId] },
})
}),
},
commands: {
prefix: "!",
commands: {
help: {
description: "List the commands",
// The first page holds up to 2,000 characters, enough for this bot's commands
execute: ({ help, reply }) => reply(help()[0] ?? "No commands"),
},
ping: {
description: "Check that the bot is online",
execute: ({ reply }) => reply("Pong!"),
},
greet: {
description: "Greet someone by name",
arguments: { name: { type: "text", rest: true } },
cooldown: { durationMs: 5_000, per: "user" },
execute: ({ values, reply }) => reply(`Hello, ${values.name}!`),
},
announce: {
description: "Post an announcement card",
arguments: { text: { type: "text", rest: true } },
guard: guards.requirePermissions(["ManageMessages"]),
execute: ({ message, values, reply }) => {
const card = builders
.embed()
.title("Announcement")
.description(values.text)
.color("#3b82f6")
.footer({ text: `Posted by ${message.author.username}` })
return reply({ embeds: [card] })
},
},
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main)
await Effect.runPromiseExit(runBot({ token: process.env.FLUXER_BOT_TOKEN, processSignals: true, ...bot }))
```
All three versions are in the [small-bot example folder](https://github.com/NeonTechSpace/Fluxerly.js/tree/main/projects/sdk/examples/small-bot). The [Effect learning path](https://fluxerly.neontechspace.com/docs/effect-first-bot.md) introduces the Effect concepts used here
---
# Run a bot with the SDK
What runBot does from start to stop, and what stays with the application
The `runBot` function runs a whole bot from one options object. It creates the client, registers every handler and command before connecting, keeps the connection alive and stops cleanly. The [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) bot is a complete example, and no separate lifecycle file is needed
## From start to stop
1. Check: The `runBot` call checks every option first. An unknown event name or an invalid command throws `ConfigurationError` before anything connects. A missing token is logged with a hint instead, the run ends with exit code 1, and `runBot` returns the error
2. Register: Event handlers and commands are registered, then the optional `setup(client, { signal })` callback runs for other startup work. Timers and background work belong in [scheduled tasks](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#run-work-later-or-on-a-schedule), which stop with the bot. For other work, the `signal` aborts when the bot begins stopping. A failed `setup` stops the bot before it connects
3. Connect: The client connects to the gateway and handlers start receiving events. Messages written by bots, including the bot's own replies, skip handlers and commands unless `ignoreBots` is `false`
4. Run: The SDK reconnects after a lost connection and keeps each [handler](https://fluxerly.neontechspace.com/docs/glossary.md#handler) running. A failed handler is not retried and does not stop the bot. Its error is logged in full, or sent to `onError` when one is set. If a handler's subscription closes while the bot is running, the bot stops with `CriticalWorkerStoppedError`
5. Stop: Ctrl+C (SIGINT) and SIGTERM stop the bot unless `processSignals` is `false`, while the Effect API handles them only with `processSignals: true`. A `signal` option stops it from application code. Stopping accepts no new events and gives running handlers and scheduled tasks up to 5 seconds to finish, a time the `drainMs` option changes. Then it cancels the work still running through its `signal`, closes the connection and waits for the SDK's cleanup. The stop request and the shutdown duration are logged at Info, and a failed cleanup step is logged at Error and still reported by the run
6. Report: After a failure the bot could not recover from, such as a rejected token, the runner logs that failure once and sets `process.exitCode` to 1. A normal stop reports nothing
7. Return: The returned [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) is Ok after a normal stop, or an Err with the failure
The [deploying guide](https://fluxerly.neontechspace.com/docs/deploying.md#what-happens-on-shutdown) lists each shutdown step. Importing the SDK adds no signal handlers, and `runBot` removes its own when the bot stops. It never exits the process
## What each handler receives
In the default API, each event handler receives one context object with `event`, `client`, `signal` and `context`, the same `EventContext` a `client.on` handler receives. Effect handlers receive `event`, `client` and `context` without a signal, because stopping the bot interrupts their Effect instead. A `messageCreate` handler also receives `message` and `reply`
The `reply` helper accepts a string or full message content and already applies the handler's cancellation signal. Return its Result so a failed reply is reported like a thrown error, as [reliability](https://fluxerly.neontechspace.com/docs/reliability.md#return-the-replys-result) explains. In the Effect API, `reply` returns an Effect. Return it or compose it into the handler's Effect so the SDK can run and interrupt it
By default `messageCreate` handlers run up to eight at a time and other events one at a time. A burst that fills a handler's queue drops the oldest waiting event with a Warn record instead of stopping the bot. [Configuration](https://fluxerly.neontechspace.com/docs/configuration.md#events-and-the-gateway) shows how to change this for one event
## Run code once the bot is connected
There is no ready event, and `setup` runs before the bot connects. For work that needs a connection, watch the client's state from `setup`. This function posts one message the first time every shard is connected:
```ts
import type { Client } from "@neontechspace/fluxerly"
export function announceWhenConnected(client: Client, channelId: string) {
const observer = client.observeState((state) => {
if (state !== "Connected") return
observer.close()
return client.messages.send(channelId, "The bot is online")
})
}
```
Remove the `close()` call to run again after each reconnect, although a slow listener can skip states. A throw or returned Err goes to `onError` or the log. Being connected does not mean the caches already hold every community. In the Effect API, `client.observeState()` returns a Stream of the same states
## Run work later or on a schedule
The `client.schedule` method runs a task after a delay or repeatedly, and the bot owns it. Call it from `setup`, an event handler or a command. It returns at once, so a command that schedules a reminder finishes and frees its command slot, as in the [commands guide](https://fluxerly.neontechspace.com/docs/commands.md#convert-arguments-before-execution). This function posts a status message every hour once `setup` calls it with the bot's client:
```ts
import type { Client } from "@neontechspace/fluxerly"
export function postHourlyStatus(client: Client, channelId: string) {
return client.schedule((signal) => client.messages.send(channelId, "Still running", { signal }), {
name: "hourly status",
intervalMs: 60 * 60 * 1_000,
})
}
```
Pass `delayMs` to run a task once after a delay, or `intervalMs` to repeat it. Without options the task runs once right away, which suits background work started in `setup`. A repeating task waits `intervalMs` before its first run unless `delayMs` says otherwise, and each later run starts `intervalMs` after the previous one ended, so runs never overlap. The returned task's `close()` cancels its later runs
A task that throws, rejects or returns an Err result is reported to `onError`, or logged at Error with the code `lifecycle.taskFailed`. The optional `name` appears in that record and in the report's `taskName`, so failures of different tasks stay apart. A repeating task keeps running after a failed run, so one network error does not end it, and a problem that lasts is reported at every run. To stop after a failure, the task can call `close()` itself
When the bot stops, tasks that have not run yet are cancelled. A requested stop lets a run in progress finish within the `drainMs` window, then cancels it through its `signal`. One Info record with the code `lifecycle.tasksCancelled` counts the tasks that stopping cut short. Tasks live in memory only, so a restart loses pending reminders. Keep work that must survive a restart outside the SDK, as in [the reminder recipe](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#keep-reminders-across-restarts)
In the Effect API the task is an Effect, as in `client.schedule(client.messages.send(channelId, "Still running"), { intervalMs: 3_600_000 })`, and the call returns an Effect to run. Each run keeps the services of the code that scheduled it, and stopping the bot interrupts a run in progress
### Run a task every day at a set time
An `intervalMs` of one day drifts by each run's length and shifts by an hour when daylight saving time starts or ends. To run at a set local time, schedule one run at a time and schedule the next one when it starts:
```ts
import type { Client } from "@neontechspace/fluxerly"
// The first 09:00 after a time, in the process's time zone, which the TZ environment variable sets, such as TZ=Europe/Berlin
function nextNine(after: Date) {
const next = new Date(after)
next.setHours(9, 0, 0, 0)
if (next <= after) next.setDate(next.getDate() + 1)
return next
}
export function postEveryMorning(client: Client, channelId: string, at = nextNine(new Date())) {
client.schedule(
(signal) => {
postEveryMorning(client, channelId, nextNine(at))
return client.messages.send(channelId, "Good morning", { signal })
},
{ delayMs: Math.max(0, at.getTime() - Date.now()) },
)
}
```
Call `postEveryMorning` once from `setup`. Each run schedules the next 09:00 after its own, not after the current time, so a timer that wakes a moment early cannot post twice. Scheduling the next run first keeps the series going when a send fails
### Keep reminders across restarts
The SDK does not own storage, so the application saves each reminder in its own store when it is created and schedules it again after a restart. This example supports integer delays up to 2,147,483,647 ms, about 24.9 days
A longer or non-integer delay makes `addReminder` reject with `RangeError` before anything is saved, so for a longer reminder, the application has to wait until the delay fits. This example keeps the due time, channel ID and text in a JSON file, and a real bot would use its database
Call `addReminder` from a command, such as the `remind` command in the [commands guide](https://fluxerly.neontechspace.com/docs/commands.md#convert-arguments-before-execution), and pass `restoreReminders` as the `setup` option of `runBot`
```ts
import { readFile, rename, writeFile } from "node:fs/promises"
import type { Client } from "@neontechspace/fluxerly"
type Reminder = { id: string; dueAt: number; channelId: string; text: string }
const file = "reminders.json"
const saved = new Map()
let writing = Promise.resolve()
// One write at a time, so the file ends with the latest list. Each list goes to a temporary file that then replaces the
// saved one, so a process stopped during a write leaves the previous list readable. A failed write reaches its caller and
// blocks no later write
function save() {
writing = writing
.catch(() => {})
.then(async () => {
await writeFile(`${file}.tmp`, JSON.stringify([...saved.values()]))
await rename(`${file}.tmp`, file)
})
return writing
}
function scheduleReminder(client: Client, reminder: Reminder) {
client.schedule(
async (signal) => {
const sent = await client.messages.send(reminder.channelId, reminder.text, { signal })
if (sent.isErr()) return sent // The SDK reports the failure and the reminder stays saved
saved.delete(reminder.id)
await save()
},
{ delayMs: Math.max(0, reminder.dueAt - Date.now()) },
)
}
export async function restoreReminders(client: Client) {
const json = await readFile(file, "utf8").catch((error) => {
if (error.code !== "ENOENT") throw error
return "[]"
})
for (const reminder of JSON.parse(json) as Reminder[]) {
saved.set(reminder.id, reminder)
scheduleReminder(client, reminder)
}
}
// The reminder is saved before it is scheduled, so a failed save leaves nothing to send later
export async function addReminder(client: Client, channelId: string, delayMs: number, text: string) {
if (!Number.isInteger(delayMs) || delayMs < 0 || delayMs > 2_147_483_647)
throw new RangeError(`Unsupported delay: ${delayMs} ms`)
const reminder = { id: crypto.randomUUID(), dueAt: Date.now() + delayMs, channelId, text }
saved.set(reminder.id, reminder)
try {
await save()
} catch (error) {
saved.delete(reminder.id)
throw error
}
scheduleReminder(client, reminder)
}
```
On every start, `restoreReminders` schedules each saved reminder with the time left until it is due, or zero when it is already overdue. A failed save makes `addReminder` reject without scheduling anything. A reminder leaves the store only after its message was sent. A failed send returns the Err result, so the SDK reports it as a failed run, and the reminder stays saved for the next start to retry. A missing file means no reminders yet, while any other read error stops the bot before it connects
A reminder can be sent twice when a send's response is lost, or when the bot stops after sending it and before removing it. The example does not handle several processes sharing one store
In the Effect API the scheduled task is an Effect that sends the message and then removes the reminder, as in `client.messages.send(channelId, text).pipe(Effect.andThen(remove))` with `remove` as an Effect. A failed send skips the removal and is reported like any failed run, and `setup` returns the Effect that restores the saved reminders
## What the application owns
The application supplies the token and handlers and decides how to report errors. It also owns everything outside the SDK:
- Work outside the drain: A returned handler Promise, a running scheduled task and their REST requests get the drain window to finish, 5 seconds by default, set by `drainMs`. Track detached Promises, timers not started with `client.schedule` and work that needs more than that window, as shown in [application supervision](https://fluxerly.neontechspace.com/docs/application-supervision.md#drain-application-owned-work)
- Other resources: Close database connections, timers and servers after `runBot` resolves, so the process can exit
- Restarts: A process manager or a new `runBot` call starts a new client. Without a session store, restarting does not replay missed events, while a [saved session](https://fluxerly.neontechspace.com/docs/sharding.md#resume-after-a-restart) can let a new client resume from its saved sequence. Failed handlers are not retried
- Durable work: Store data and jobs that must survive a restart outside the SDK
## Choose the API
The JavaScript and TypeScript `runBot` returns a Result for expected failures and reports them itself, so the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md) bot only awaits it. Invalid options still throw `ConfigurationError` at once, and an unexpected SDK defect rejects with `SdkDefect`. Set `reportFailure: false` when the application handles the returned failure and the exit status itself, for example to restart the bot in the same process
The [Effect `runBot`](https://fluxerly.neontechspace.com/docs/effect-first-bot.md) returns an Effect and keeps access to application services, scoped resources and failure causes. It reports a failure the same way, so running it with `Effect.runPromiseExit` is enough. Run it once from the application's top-level code instead of starting a separate runtime inside handlers
For prefix commands, pass `commands`, as shown in [commands](https://fluxerly.neontechspace.com/docs/commands.md). The lower-level `createClient` and subscription APIs remain available for flows that need direct control of the client's lifetime. See [application supervision](https://fluxerly.neontechspace.com/docs/application-supervision.md) for watching required subscriptions in application code
---
# Support and compatibility
Separate SDK support, instance availability and account permissions before deploying a bot
Before production use, check how the application handles failures, restarts and deployment with the exact SDK version installed
## Runtime and upgrade requirements
| Area | Current policy |
| ----------------- | ------------------------------------------------------------------------------------------------ |
| Runtime | Node.js 26.13.0 or newer (`>=26.13.0` minimum required to build and run a bot) |
| Modules | ESM only, with `"type": "module"` in `package.json` or `.mjs` files |
| Package managers | npm, pnpm or Bun installs the package, and Node.js runs the bot |
| JavaScript | No TypeScript compiler requirement |
| TypeScript | TypeScript 7, not TypeScript 6 or earlier, with `@types/node` for the Node.js types |
| Native Effect | Effect 4.1.2 or a later Effect 4 release, in the range the installed package lists |
| Web browsers | Not supported. A bot runs as a Node.js program, not inside a web page |
| Operating systems | Hosted CI uses Ubuntu. A passing Ubuntu run does not qualify every operating system or container |
| License | Free and open source under the Apache License 2.0 |
Check the installed package's manifest for its Node.js and Effect requirements. CI also tests newer Node.js LTS releases, and a newer tested Node.js version does not raise the minimum required to build a bot unless Fluxerly requires a feature from that release. The default API needs Effect internally, and npm, pnpm or Bun normally installs that dependency automatically. Native Effect code must use a version within the Effect peer range listed there (`^4.1.2`), not Effect 3 or an Effect 4 prerelease. Since SDK 1001.0.0 the range starts at Effect 4.1.2, because Effect 4.1.0 fails to type-check in a TypeScript project that has the Node.js types but no `DOM` library
Stable releases follow Epoch Semantic Versioning, so only a new major version or epoch can break existing code, and minor and patch releases are safe to take. Nightly builds can include breaking changes at any time
## Check SDK, instance and account support
Before relying on an operation, check three separate things:
1. **Does the SDK implement the operation?** Consult the installed version's [API reference](https://fluxerly.neontechspace.com/docs/api/). A method available in newer documentation may not exist in an older package
2. **Does the selected instance implement and enable it?** Discovery exposes reviewed endpoint and upload metadata, not a complete endpoint capability registry
3. **May this account perform it on this resource?** Account type, OAuth scope, community membership and permissions remain provider decisions at request time
How the client reads instance details
A provider code-version number does not say which API routes or permissions are available. The client reads instance details once and does not refresh them while it runs. A 404 response alone cannot tell whether a feature is missing, a resource is unavailable or access is hidden
The existing presigned-upload flag is an advertised Boolean used for attachment routing. Missing or malformed required discovery data fails resolution rather than becoming an assumed capability. Features without a reviewed discovery field remain unknown. Neither a guessed capability nor another instance's metadata should select a credential destination
## Get help
Use [troubleshooting](https://fluxerly.neontechspace.com/docs/troubleshooting.md) and the [FAQ](https://fluxerly.neontechspace.com/docs/faq.md) to diagnose a problem. Ask usage questions in [Q&A](https://github.com/NeonTechSpace/Fluxerly.js/discussions/categories/q-a), propose features in [Ideas](https://github.com/NeonTechSpace/Fluxerly.js/discussions/categories/ideas), and report reproducible SDK problems with the [bug-report form](https://github.com/NeonTechSpace/Fluxerly.js/issues/new?template=bug_report.yml). Public issues cover only Stable releases in the current major. A problem found on a nightly must also reproduce on one of those Stable releases
Report a security vulnerability privately, as the [repository security policy](https://github.com/NeonTechSpace/Fluxerly.js/security/policy) describes, through GitHub's private vulnerability reporting. Do not post vulnerabilities in public issues, pull requests or discussions
## Safe failure reports
To report a failure, include the exact SDK, Effect and Node versions, operating system, default or native entry point, operation name, safe error code, expected result and a minimal reproduction using a controlled test resource. The output of `describeError(error)` supplies the code, hint and cause chain. Say whether the failure came from a local fake provider or a live instance, and which recovery or cleanup checks ran
Exclude tokens, authorization headers, OAuth codes and refresh tokens, webhook credentials, signed attachment URLs, private message bodies and unredacted request or response dumps. Reduce identifiers and payloads to synthetic examples. Application logs need independent redaction even when SDK diagnostics omit sensitive fields
---
# Test a bot without Fluxer
Run commands and handlers against an in-memory Fluxer with the testing entry points, without a token or network
The `@neontechspace/fluxerly/testing` entry point creates a real client connected to an in-memory Fluxer. A test sends the bot a fake message or event and checks the requests the bot made. No token, network or Fluxer account is needed, and the events pass through the SDK's own decoding, [caches](https://fluxerly.neontechspace.com/docs/glossary.md#cache) and [handlers](https://fluxerly.neontechspace.com/docs/glossary.md#handler)
## Share the bot's options with its tests
A bot started with [`runBot`](https://fluxerly.neontechspace.com/docs/starter-lifetime.md) is tested with `createTestBot`, which takes the same options. It covers handlers, commands and setup but not `runBot`'s supervision, so a stopped subscription, such as one set to `overflow: "stop"` whose queue fills, does not stop the test bot. The Effect test bot has the same limit. Test `runBot`'s terminal failures and process-signal handling separately, and call `testBot.client.shutdown({ drainMs })` to test a drain
The bot file that `fluxerly init` writes, shown in the [quick start](https://fluxerly.neontechspace.com/docs/quick-start.md), exports those options without the token as `bot` and starts the bot only when Node.js runs the file:
```js
import { defineBot, runBot } from "@neontechspace/fluxerly"
// The bot's options without its token, so its test can run them through createTestBot without a token or a network
export const bot = defineBot({
commands: {
prefix: "!",
commands: {
// Returning the reply reports a failed send to the log
ping: { execute: ({ reply }) => reply("Pong!") },
},
},
})
// Running this file starts the bot, while importing it from a test does not.
// A failure that stops the bot, such as a rejected token, is logged and sets a failing exit code
if (import.meta.main) await runBot({ token: process.env.FLUXER_BOT_TOKEN, ...bot })
```
A test imports `bot` from this file, so the bot and its tests run the same events, commands and setup. The `defineBot` function returns the options unchanged and keeps the types of command arguments, which an object annotated with `BotOptions` loses. A larger bot can keep its options in a module of their own instead, such as `bot-options.ts`, which both the bot file and the tests import
## Write a first test
This test uses `node:test`, the test runner built into Node.js, so nothing else needs installing. A project from `fluxerly init` already has a similar test as `bot.test.js`, or `bot.test.ts` for TypeScript, and runs it with `npm test`, `pnpm test` or `bun run test`
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { defineBot } from "@neontechspace/fluxerly"
import { createTestBot } from "@neontechspace/fluxerly/testing"
// In a project, import bot from ./bot.ts. It is repeated here so the example runs on its own
const bot = defineBot({
commands: {
prefix: "!",
commands: {
ping: {
description: "Check that the bot replies",
execute: ({ reply }) => reply("Pong!"),
},
},
},
})
test("!ping replies Pong!", async () => {
await using testBot = createTestBot(bot)
await testBot.ready()
const replies = await testBot.say("!ping")
assert.deepEqual(testBot.failures(), [])
assert.deepEqual(
replies.map((message) => message.content),
["Pong!"],
)
})
test("other messages get no reply", async () => {
await using testBot = createTestBot(bot)
await testBot.ready()
assert.deepEqual(await testBot.say("hello"), [])
})
test("a command that throws is reported", async () => {
await using testBot = createTestBot({
commands: {
prefix: "!",
commands: {
broken: {
execute: () => {
throw new Error("Not implemented yet")
},
},
},
},
})
await testBot.ready()
testBot.emit("MESSAGE_CREATE", testBot.fixtures.message({ content: "!broken" }))
await testBot.idle()
assert.deepEqual(
testBot.failures().map((record) => record.code),
["commands.failed"],
)
})
```
Run every test file in the project:
```sh
node --test --test-timeout=10000 --test-force-exit
```
Node.js finds test files such as `bot.test.js` and `bot.test.ts` and runs TypeScript directly
## What the test does
1. The `createTestBot` call creates a test client and registers the bot's events and commands on it, as `runBot` would. The unset token falls back to a test token, and `processSignals` is ignored. The `await using` declaration shuts the client down when the test ends, even after a failed assertion
2. The `ready()` call runs the bot's `setup`, if it has one, connects to the fake gateway and waits for READY
3. The `say` call delivers a message from a fake user, exactly as Fluxer would send it, waits until the bot has stopped working and returns the messages the bot sent meanwhile. The fake Fluxer API answers each message the bot sends with that message, so no response needs registering. The list shows what the bot tried to send, even when `rest.respond` rejected the request, and a failure that an `onError` hook handled does not appear in `failures()`
4. The test checks that nothing failed, then the content of what the bot sent, and an empty list shows that the second test's message was ignored
Check `failures()` before reply assertions when using `await using`. If an assertion and the cleanup both fail, Node.js can show only `SuppressedError`. A test that expects a failure should check that failure instead
For other events, the `emit` call delivers a Fluxer event built by `fixtures`, and `idle()` waits until the bot has stopped working, as the third test shows
To control how the fake Fluxer API answers a request, `rest.respond` registers a response and returns a route whose `next()` waits for the next request it answers. These waits have no deadline unless `timeoutMs` is passed, as in `bot.idle({ timeoutMs: 2_000 })`, so run tests with `node --test --test-timeout=10000 --test-force-exit` to fail a bot that never settles. Without `--test-force-exit`, Node.js reports the timeout but the process keeps running
Use fake timers in a test
A `timeoutMs` on `next()`, `idle()` or `say` uses real timers, so faking the global timers does not change it. The SDK runs its work on `setImmediate`, so fake timers must leave `setImmediate` real, as in Vitest's `vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date"] })`. When `setImmediate` is faked, no handler can run, and `idle()` rejects with `ConfigurationError` instead of settling
Fake timers do not advance the SDK's own clock on Node.js, so a `client.schedule` delay still takes real time. Use the manual test clock from [Test work that waits](https://fluxerly.neontechspace.com/docs/testing.md#test-work-that-waits) instead. Native Effect tests can use `TestClock`, as the [Effect testing guide](https://fluxerly.neontechspace.com/docs/effect-application-testing.md) shows
The third test passes its own options with a command that throws. Without an `onError` hook (see [handle failures in one place](https://fluxerly.neontechspace.com/docs/logging.md#handle-failures-in-one-place)), the failure is logged as `commands.failed`. The `failures()` method returns such unhandled failures and marks them as expected. When a handler or command throws or returns a failed Result without `onError` and the test never reads the failure from `failures()`, shutdown rejects with `UnhandledTestFailuresError`, so a broken handler fails the test even without an assertion
Requests without a registered response
A message send or edit that matches no `rest.respond` route receives the sent message back, as if Fluxer accepted it. Any other request without a route receives a 404 shaped like Fluxer's, and `logs()` gains a `testing.unmatchedRequest` Warn record. When a command returns a request that fails this way, the failure is logged as `commands.failed` and counts like a thrown error. The `failures()` method returns it, and shutdown rejects unless the test read it
## Test work that waits
A test client runs the SDK's timers on real time, so a reminder set for ten minutes takes ten minutes. With `clock: "manual"`, they follow a test clock that starts at 0 and moves only when the test calls `advance(ms)`
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { defineBot } from "@neontechspace/fluxerly"
import { createTestBot } from "@neontechspace/fluxerly/testing"
const bot = defineBot({
commands: {
prefix: "!",
commands: {
remind: {
description: "Repeat a note after a delay",
arguments: {
delay: { type: "duration", min: 1_000, max: 3_600_000 },
note: { type: "text", rest: true },
},
execute: ({ client, message, values, reply }) => {
client.schedule((signal) => client.messages.reply(message, values.note, { signal }), {
delayMs: values.delay,
})
return reply("Reminder set")
},
},
},
},
})
test("!remind replies with the note once its delay has passed", async () => {
await using testBot = createTestBot({ ...bot, clock: "manual" })
await testBot.ready()
const replies = await testBot.say("!remind 10m stretch")
assert.deepEqual(testBot.failures(), [])
assert.deepEqual(
replies.map((message) => message.content),
["Reminder set"],
)
await testBot.advance(10 * 60_000)
assert.deepEqual(testBot.failures(), [])
assert.deepEqual(
testBot.requests().map((request) => (request.body as { content?: unknown }).content),
["Reminder set", "stretch"],
)
})
```
The `advance` call stops at each SDK deadline on the way and runs the work due there, so an interval task advanced by three intervals runs three times. Before moving on, it waits for bot code that awaits its own database, files or timers, as `idle()` does
The test clock also drives `waitFor` and collector timeouts, cooldowns in the command router's own store, cache expiry, request pacing and the heartbeat. A cooldown store passed to a command, such as `commands.memoryCooldowns()`, keeps real time, and so do `Date.now()` and timers in the bot's own code and the `timeoutMs` of `next()`, `idle()` and `say`. A bot with more than one shard or automatic sharding cannot use the manual clock
A command that waits on the test clock, such as one that awaits `waitFor`, finishes only once the clock moves. The `say` call then resolves with what the bot sent before it started waiting, and `advance` lets the command finish:
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { defineBot } from "@neontechspace/fluxerly"
import { createTestBot } from "@neontechspace/fluxerly/testing"
const quiz = defineBot({
commands: {
prefix: "!",
commands: {
quiz: {
description: "Wait 30 seconds for an answer",
execute: async ({ client, reply }) => {
const answer = await client.waitFor("messageCreate", { timeoutMs: 30_000 })
return reply(answer.isErr() ? "Time is up" : "Answered")
},
},
},
},
})
test("!quiz gives up after 30 seconds", async () => {
await using testBot = createTestBot({ ...quiz, clock: "manual" })
await testBot.ready()
assert.deepEqual(await testBot.say("!quiz"), [])
await testBot.advance(30_000)
assert.deepEqual(
testBot.requests().map((request) => (request.body as { content?: unknown }).content),
["Time is up"],
)
})
```
## Test handlers registered with client.on
Code that registers handlers on a client with `client.on`, instead of through `runBot`, is tested with `createTestClient`. It creates the same test client without bot options. Unlike `runBot` handlers, `client.on` handlers receive the event itself and have no `reply`, so they send through client methods
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import type { Client } from "@neontechspace/fluxerly"
import { createTestClient } from "@neontechspace/fluxerly/testing"
// The application passes its own client and welcome channel
export function installWelcome(client: Client, channelId: string) {
return client.on("guildMemberAdd", (member) => client.messages.send(channelId, `Welcome, ${member.userId}!`))
}
test("new members are welcomed", async () => {
await using bot = createTestClient()
const sent = bot.rest.respond("POST /channels/:id/messages", { body: bot.fixtures.message() })
installWelcome(bot.client, bot.fixtures.ids.channel)
await bot.ready()
bot.emit("GUILD_MEMBER_ADD", bot.fixtures.member())
const request = await sent.next()
assert.match(String((request.body as { content?: unknown }).content), /^Welcome/)
})
```
## Match gateway event filtering
The test gateway keeps the `gateway.ignoredEvents` list sent at Identify. An `emit` call throws `ConfigurationError` instead of delivering a dispatch Fluxer would suppress, and the rejected dispatch consumes no sequence number. This catches tests that would pass only because the fake gateway delivered an event the real bot cannot receive
With `gateway.ignoredEvents: "auto"`, register handlers and waits before `ready()` so Identify sees them. Collectors need a connected client, so start them after `ready()`, and register a `messageCreate` handler before `ready()` when a test collects messages. A bot's handlers, commands and setup registrations are already installed at that point. A late registration cannot undo the current session's filtering, and Resume keeps that list. A new Identify recomputes automatic filtering. For an explicit list, remove the source dispatch type from the options before creating the client, or use `gateway.ignoredEvents: []` to disable suppression
Suppressed `MESSAGE_CREATE` still arrives for a direct bot mention, `@here` or `@everyone`, but not merely for a role mention, an unmentioned direct message or the bot's own message. Reaction batches use their source event's filter: Ignoring `MESSAGE_REACTION_ADD` prevents `MESSAGE_REACTION_ADD_MANY`, while ignoring `MESSAGE_REACTION_ADD_MANY` alone does not. Under automatic filtering, a `messageReactionAddMany` handler retains that source dispatch
## Inspect what the bot sent
The test client records everything, without the token or Authorization header:
- HTTP requests: The `requests()` method lists each one with its method, path, query, parsed JSON body and uploaded files
- Gateway commands: The `commands()` method lists what the client sent to the gateway, such as presence updates
- Logs: The `logs()` method returns the records the client produced, which are kept out of the console
- Failures: The `failures()` method returns the Error records of handler and command failures no `onError` hook received, even when the logging level or deduplication keeps them out of `logs()`
- Counters: The `counters()` method returns the same running totals as `client.diagnostics().counters`
Each `rest.respond` call returns a route whose `requests()` lists only the requests it answered, `next()` waits for the next one and `remove()` stops it. The newest matching response wins. A matcher can be a `"METHOD /path/:param"` string, a RegExp, an object or a function
A handler that throws makes the request fail as a network error, and that does not always fail the test. Check request contents with `next()` or `requests()` after the call instead
Fixtures, shards and reconnects
Each test client has its own `fixtures`, whose builders return snake_case wire payloads for users, the bot user, guilds, `GUILD_CREATE` bodies, channels, roles, members and messages. Their defaults refer to one community, one channel and one author, and `fixtures.ids` holds those IDs. The IDs are deterministic, so the same calls produce the same IDs in every run. The shared `fixtures` export and `createFixtures()` build payloads outside a test client
Pass `{ shardId }` to `emit` to choose the receiving [shard](https://fluxerly.neontechspace.com/docs/glossary.md#shard) in a sharded client. Call `disconnect({ code })` to close a shard's connection from the gateway side and watch the client resume, or fail for a code that ends the session. Every recoverable code resumes the same session, including 4007, so `sessionEpoch` stays the same
Pass `endSession: true` to make the test gateway forget the session first, so the client identifies a new one and the next event's `context.sessionEpoch` is higher
The `createTestClient` function accepts every `createClient` option except `transport` and `instance`, which the test transport owns. The `createTestBot` function accepts the bot's `runBot` options and ignores `signal`, `processSignals`, `reportFailure` and `drainMs`
## Test a denied permission
The default fixture author owns the community and so has every permission. To test a denied permission, give the community a different owner and answer the reads the guard makes
```ts
import assert from "node:assert/strict"
import { test } from "node:test"
import { guards } from "@neontechspace/fluxerly"
import { createTestBot } from "@neontechspace/fluxerly/testing"
test("!ban needs BanMembers", async () => {
await using testBot = createTestBot({
commands: {
prefix: "!",
commands: {
ban: {
guard: guards.requirePermissions(["BanMembers"]),
execute: ({ reply }) => reply("Banned"),
},
},
},
})
const { guild, channel, user, bot: botId } = testBot.fixtures.ids
testBot.rest.respond(`GET /guilds/${guild}`, { body: testBot.fixtures.guild({ owner_id: botId }) })
testBot.rest.respond(`GET /guilds/${guild}/members/${user}`, { body: testBot.fixtures.member() })
testBot.rest.respond(`GET /guilds/${guild}/roles`, { body: [testBot.fixtures.role({ id: guild, permissions: "0" })] })
testBot.rest.respond(`GET /channels/${channel}`, { body: testBot.fixtures.channel() })
await testBot.ready()
const replies = await testBot.say("!ban")
assert.ok(!replies.some((message) => message.content === "Banned"))
})
```
## Test Effect programs
The `@neontechspace/fluxerly/effect/testing` entry point provides the same `createTestBot` and `createTestClient` for the Effect API. Its test clients are scoped: Closing the Scope shuts the client down, and `ready`, `emit`, `next` and `idle` are Effects. The [Effect application testing guide](https://fluxerly.neontechspace.com/docs/effect-application-testing.md) covers testing Effect bots, including time-based behavior
The reference lists every control and option: [Testing](https://fluxerly.neontechspace.com/docs/api/testing/) for the default API and [Effect testing](https://fluxerly.neontechspace.com/docs/api/effect-testing/) for the Effect API
---
# Create and manage threads
Create threads and forum posts, archive, lock and list threads, search them, manage their members and read their state
A thread is a channel inside a text, announcement, forum or media channel that holds its own messages. Fluxer has three thread types. Public and private threads start in text channels, and announcement threads start in announcement channels. Every post in a forum or media channel is a public thread
The `client.threads` namespace creates, changes, lists and searches threads and manages their members. A thread is still a channel, so `channels.fetch` reads one, `channels.delete` deletes one and `messages.send` with the thread's ID posts in it. Bots can use threads without a capability setting
The examples use the default API. The Effect entry point exports the same names. Its `client.threads` methods return Effects, except `threads.iterateArchived` and `threads.iterateMembers`, which return Streams
## Recognize a thread
Channel reads, channel events, message search results and audit-log pages return threads with their own channel shapes. The `isThreadChannel` function tells a thread from any other community channel, and `type` selects one thread type
```ts
import { ChannelType, isThreadChannel, type GuildChannel } from "@neontechspace/fluxerly"
export function describeChannel(channel: GuildChannel) {
if (!isThreadChannel(channel)) return `channel ${channel.name ?? channel.id}`
const kind = channel.type === ChannelType.PrivateThread ? "private thread" : "thread"
return `${kind} ${channel.name} in channel ${channel.parentId}`
}
```
## Read thread state
A thread shape flattens Fluxer's thread metadata into `archived`, `locked`, `autoArchiveMinutes`, `archiveTimestamp` and `createdAt`. Its `parentId` names the channel that holds the thread, never a category. A private thread also has `invitable`, and a forum or media post has `appliedTagIds`
The `membership` field describes the bot's own membership when Fluxer reports it. Some reads leave it out, so its absence does not prove that the bot is not a member. The `memberCount` field is approximate and stops at 50
```ts
import { isThreadChannel, ThreadAutoArchiveMinutes, type Client } from "@neontechspace/fluxerly"
export async function threadState(client: Client, channelId: string) {
const channel = await client.channels.fetch(channelId)
if (channel.isErr()) return channel
const thread = channel.value
if (!isThreadChannel(thread)) return undefined
return {
archived: thread.archived,
archivesAfterOneDay: thread.autoArchiveMinutes === ThreadAutoArchiveMinutes.OneDay,
joinedAt: thread.membership?.joinedAt,
}
}
```
## Create a thread
The `threads.create` method starts a thread in a text or announcement channel. The type defaults to `ChannelType.PublicThread`, and a private thread is possible only in a text channel. Creating a public thread needs `CreatePublicThreads`, and a private one needs `CreatePrivateThreads`. The bot becomes the thread's first member
```ts
import { ChannelType, ThreadAutoArchiveMinutes, type Client } from "@neontechspace/fluxerly"
export async function startPlanning(client: Client, channelId: string) {
const thread = await client.threads.create(channelId, {
name: "Release planning",
type: ChannelType.PrivateThread,
autoArchiveMinutes: ThreadAutoArchiveMinutes.OneDay,
})
if (thread.isErr()) return thread
return client.messages.send(thread.value.id, "Planning starts here")
}
```
To start a public thread on an existing message instead, use `threads.createFromMessage`. The thread takes the message's ID, and a message can start only one thread. It needs `CreatePublicThreads` and `ReadMessageHistory`
```ts
import type { Client, Message } from "@neontechspace/fluxerly"
export async function discussIn(client: Client, message: Message) {
return await client.threads.createFromMessage(message, { name: "Discussion" })
}
```
## Create a forum post
In a forum or media channel, `threads.createPost` creates a post: A public thread together with its first message. The message takes the same content, embeds, files and stickers as `messages.send`, can be a [voice note](https://fluxerly.neontechspace.com/docs/messages.md#mark-media-as-explicit-or-send-a-voice-note), and its files go in the same request. The `appliedTagIds` setting applies up to 5 of the channel's tags. The [forum channel guide](https://fluxerly.neontechspace.com/docs/forum-channels.md) describes the tags and settings a forum channel has
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function reportCrash(client: Client, forumId: string, tagId: string, log: Uint8Array) {
const post = await client.threads.createPost(forumId, {
name: "Crash on start",
appliedTagIds: [tagId],
message: {
content: "The log is attached",
attachments: [{ data: log, filename: "crash.log", contentType: "text/plain" }],
},
})
return post.map(({ thread, message }) => ({ postId: thread.id, messageId: message.id }))
}
```
After a timeout or lost response, `threads.create` and `threads.createPost` may already have created the thread, and repeating them can create a second one. Read the channel's threads before repeating, and treat a failed read as still unknown. The `threads.createFromMessage` method cannot create a second thread for one message, and `channels.fetch(message.id)` shows whether it exists. If a separate `messages.send` fails after `threads.create` or `threads.createFromMessage` succeeds, the thread remains. If `threads.createPost` fails while sending its first message, Fluxer removes the new post again, so listeners see a thread create event followed by a thread delete event for it. See [uncertain writes](https://fluxerly.neontechspace.com/docs/reliability.md#send-once-when-the-outcome-is-uncertain)
## Archive, lock and pin threads
The `threads.edit` method changes the supplied settings and returns the updated thread. The thread's creator can rename it, archive it, lock it and change its archive period and tags. Unlocking, slowmode, pinning and moderated tags need `ManageThreads`. A locked thread accepts changes only from members who can manage threads, and an archived thread accepts only a change that also unarchives it
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function closeThread(client: Client, threadId: string) {
return await client.threads.edit(threadId, { archived: true, locked: true }, { auditReason: "Resolved" })
}
```
Setting `pinned` to `true` pins a forum or media post at the top of its channel, which holds at most one pinned post. Delete a thread with `channels.delete`
## List threads
The `threads.fetchActive` method returns every active thread the bot can view in a community, newest first. A private thread appears only when the bot joined it or can manage threads in its parent channel
The `threads.fetchArchived` method returns one page of archived threads of a channel. Its `scope` selects public threads, private threads or the private threads the bot joined. Reading them needs `ReadMessageHistory`, and the `private` scope also needs `ManageThreads`. The `public` and `private` scopes list the most recently archived threads first, and the `joinedPrivate` scope lists the newest threads first
The `threads.iterateArchived` method reads every page up to `maxItems` in the same order, and takes the same `scope` and starting `before`. It picks each next cursor itself: The last thread's archive time for `public` and `private`, and its ID for `joinedPrivate`. Threads archived in the same millisecond are all read unless more of them than a full page share it, and each thread is delivered once
```ts
import type { Client, GuildThreadChannel } from "@neontechspace/fluxerly"
export async function archivedThreads(client: Client, channelId: string) {
const threads: GuildThreadChannel[] = []
for await (const result of client.threads.iterateArchived(channelId, { maxItems: 500 })) {
if (result.isErr()) return result
threads.push(result.value)
}
return threads
}
```
To read pages one at a time with `threads.fetchArchived` instead, pass the last thread's `archiveTimestamp`, or its `id` for `joinedPrivate`, as `before`. Fluxer reads that cursor as strictly before, so a thread archived in the same millisecond as the last one is skipped
In every list, a thread the bot joined has `membership` set
## Search threads
The `threads.search` method finds threads of a text, announcement, forum or media channel by name, tags and archive state, and returns one page. In a forum or media channel, the page's `firstMessages` holds the posts' first messages that still exist. Searching needs `ReadMessageHistory`
When a community has no thread search index yet, Fluxer starts building one and the result has `indexing` set to `true`, no threads and `retryAfterMs`, the wait Fluxer suggests. The SDK does not retry, so search again after that wait
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function findCrashReports(client: Client, forumId: string) {
const result = await client.threads.search(forumId, { name: "crash", archived: false, limit: 10 })
if (result.isErr()) return result
if (result.value.indexing) return "The search index is still being built"
return result.value.threads.map((thread) => thread.name)
}
```
## Manage thread members
The bot joins and leaves a thread with `threads.join` and `threads.leave`. Adding a community member who can view the parent channel with `threads.addMember` needs `SendMessagesInThreads`, and removing one with `threads.removeMember` needs `ManageThreads`, unless the bot created the private thread. An archived thread accepts no membership changes
The `threads.fetchMembers` method reads one page of members in user ID order, and `threads.iterateMembers` reads every page up to `maxItems`. With `withMember`, each `ThreadMember` also holds the user's community membership. Fluxer's thread member data does not name the community, so the SDK takes it from the cached thread, or reads the thread once when it is not cached
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function memberNames(client: Client, threadId: string) {
const names: string[] = []
for await (const result of client.threads.iterateMembers(threadId, { maxItems: 500, withMember: true })) {
if (result.isErr()) return result
names.push(result.value.member?.nickname ?? result.value.member?.username ?? result.value.userId)
}
return names
}
```
## Find the thread a message started
A message that started a thread has the `MessageFlags.HasThread` bit, and its `thread` field holds that thread while it exists. A public or announcement thread started without a message posts a `MessageType.ThreadCreated` notice in the parent channel. A thread started from a message posts it only when that message is not among the channel's five newest messages, and a forum or media post never does. The notice's content is the thread name and its `messageReference` names the thread. To react to new threads, handle `threadCreate` and check `isNewlyCreated`, as [Follow threads](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#follow-threads) shows. Prefix commands never run for such a notice
```ts
import { MessageFlags, type Message } from "@neontechspace/fluxerly"
export function startedThread(message: Message) {
return ((message.flags ?? 0) & MessageFlags.HasThread) !== 0 ? message.thread : undefined
}
```
## Find where threads are available
The `guilds.fetchPage` method reports `threadsActive` for each community. It is true where the bot can use threads, forum channels and media channels
```ts
import type { Client } from "@neontechspace/fluxerly"
export async function communitiesWithThreads(client: Client) {
const page = await client.guilds.fetchPage()
return page.map((guilds) => guilds.filter((guild) => guild.threadsActive).map((guild) => guild.id))
}
```
## Thread permissions
`Permissions` includes `ManageThreads`, `CreatePublicThreads`, `CreatePrivateThreads` and `SendMessagesInThreads`. A thread has no permission overwrites of its own. Fluxer computes its permissions in the parent channel and uses `SendMessagesInThreads` in place of `SendMessages`. The `permissions.calculate` method does the same when it receives the parent as `parentChannel`, and `permissions.fetch` and the `requirePermissions` guard read the parent themselves. See [communities and permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#check-permissions-using-available-data)
---
# Diagnose a bot that is not behaving as expected
Match log lines and errors with their fixes, and separate command, worker, connection and request problems
Start with what the bot printed. The client logs startup, readiness, lost connections, rate-limit waits, shutdown and every application error by default. Each readable log line shows its record code in brackets after the category, such as `[lifecycle.connectionLost]`. Then check the operation's [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) or native Effect error. The `describeError(error)` function (or `describeError(error, { color: "auto" })` for terminal styling) prints any SDK error with its code, suggested fix, retry guidance, validation errors and cause chain
The [error and log codes](https://fluxerly.neontechspace.com/docs/codes/) page lists every code with its meaning and fix. Run [`fluxerly doctor`](https://fluxerly.neontechspace.com/docs/cli.md#check-setup-offline-with-doctor) (adding `--strict` for CI or `--json` for structured output) for an offline static check of Node.js, ESM, `tsconfig.json` `moduleResolution`, TypeScript 7, Effect, local or hoisted `node_modules` drift and POSIX `.env` permissions, or [`fluxerly triage`](https://fluxerly.neontechspace.com/docs/cli.md#investigate-failures-with-triage) to investigate a bot or SDK bug with a coding agent, pipe logs through `--log -`, capture a bounded trace with `--run`, `--timeout` and `--debug`, or emit a redacted brief with `--print`, `--out ` or `--json` (including an automatic **Detected SDK codes** table). Both `doctor` and `triage` run even on Node.js older than 26.13 to report the version check cleanly. The table below covers the most common log codes
## Match a log line with its fix
| Record code | What it means | What to do |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `configuration.invalid` with field `token` | The token was missing or empty, or it started with `Bot ` or `Bearer ` | The environment variable holding the token is probably unset. Start the bot with `node --env-file=.env bot.js` from the folder that holds `.env`, or set the variable in the shell, and pass only the token without a scheme. Surrounding spaces and one pair of quotes are removed. In a project made by `fluxerly init`, set `FLUXER_BOT_TOKEN` in the `.env` file that init wrote |
| `configuration.invalid` for an unknown option | An option name is misspelled or not supported where it was passed | The hint names the closest supported option, as in `Did you mean "logging"?`, then lists every supported one |
| `lifecycle.connectionEnded` with close 4004 | Fluxer rejected the bot token | Check that the configured value is the whole bot token, or regenerate the token in the application settings and update the configuration. The SDK does not retry a rejected token |
| `lifecycle.connectionEnded` with close 4011 or 4010 | The gateway requires more [shards](https://fluxerly.neontechspace.com/docs/glossary.md#shard), or rejected the shard assignment | Set `sharding: "auto"` for a bot in one process, or configure `sharding` with the total shard count the gateway expects. See [sharding](https://fluxerly.neontechspace.com/docs/sharding.md) |
| `lifecycle.resharded` | Fluxer closed a shard with 4011 under `sharding: "auto"` or without `sharding` settings, so the SDK counted the communities again and moved every shard to a larger plan. Events sent during the move were missed | Nothing, unless it repeats. Without `sharding` settings, set `sharding: "auto"` so the next start opens enough shards at once. After 3 moves within an hour, the next 4011 ends the client with `lifecycle.connectionEnded` |
| `supervisor.resharded` | A child's shard was closed with 4011 under the supervisor's `totalShards: "auto"`. At Warn, the supervisor stopped every child, counted again and started a larger plan. At Error, it had already moved 3 times within an hour or reached 16,384 shards, so it shut down | At Error, check why the community count keeps growing, or choose a larger numeric `totalShards` |
| `lifecycle.connected` | Every shard is connected. The message names the bot and how many communities it is in. At Warn, the bot is not in any community | At Warn, open the installation link in the message and add the bot to a community. See [Create a bot](https://fluxerly.neontechspace.com/docs/create-a-bot.md#3-invite-the-bot-to-a-community) |
| `lifecycle.retry` | A startup connection attempt failed and the SDK is trying again | Nothing, unless startup then fails. The message names the reason and the delay |
| `lifecycle.connectionLost` | A connection dropped and the SDK is reconnecting | Nothing, unless it repeats. The message names the close code, its meaning and whether the session resumes |
| `lifecycle.sessionReset` | The session could not resume, so the next connection starts a new one | Events sent while disconnected are not replayed. Refresh state that matters |
| `lifecycle.cacheRefill` | Shards resumed sessions from the [session store](https://fluxerly.neontechspace.com/docs/sharding.md#resume-after-a-restart), which carry no community data, so the SDK refilled the enabled community, role and channel caches through REST. At Warn, some communities failed or the refill stopped early, such as when the community list repeated a page | At Warn, read the message and any error. The missing cache entries fill as events and requests arrive |
| `lifecycle.draining`, `lifecycle.drained` | A shutdown with `drainMs` stopped accepting new events and waited for running handlers, their waiting events, running scheduled tasks and REST requests. A `lifecycle.drained` record means all of it finished in time | Nothing |
| `lifecycle.drainTimedOut` | The drain time ran out, so shutdown cancelled the work that had not finished. The fields name how many handlers, events, tasks and requests | Make handlers and tasks finish sooner, or raise `drainMs` if the process may take longer to stop |
| `events.discarded` | A subscription stopped with events still waiting in its queue, so they never reached it. At Info the client was closing, and at Debug the subscription itself closed. The count is in `fields.discarded`, and `diagnostics().counters.eventsDropped.closed` includes it | At Info, shut down with `drainMs` to let waiting handler events run first |
| `events.refused` | A draining shutdown received events that open subscriptions or collectors would have received and did not deliver them, because it accepts no new events. The count is in `fields.refused`, and `diagnostics().counters.eventsDropped.closed` includes it | Nothing |
| `rest.busy` | A request failed with reason `busy` because the REST queue or the upload byte budget was full. It is logged at most once a minute, and every such failure is counted in `diagnostics().counters.restBusy` | Send fewer requests at once, or raise the limit the message names |
| `rest.rejected` | The SDK logs HTTP 401 or 403 rejections at Warn even when the application handles the Result, because they usually indicate a lasting token or permission problem. A webhook client also logs a wrong or deleted webhook token here, which Fluxer refuses with HTTP 404. It holds the Warn for up to one second, replacing it with the handler or command's failure record only if that callback fails with the same rejection while it is held and no `onError` hook is configured for that failure. [Identical repeats collapse](https://fluxerly.neontechspace.com/docs/logging.md#collapse-repeated-errors) into one record per minute by default | Follow the record's hint. A bot that expects these rejections can set the `rest` category to `error`, as [logging](https://fluxerly.neontechspace.com/docs/logging.md#choose-levels-and-categories) shows |
| `ratelimit.wait` | A request waited for Fluxer's [rate limit](https://fluxerly.neontechspace.com/docs/glossary.md#rate-limit) | Spread out bursts on the named route. Waits under one second are logged at Debug |
| `ratelimit.deadline` | A rate limit's required wait would pass the request deadline, so the request failed without waiting | Raise the operation's `timeoutMs`, or retry after the wait named in the record |
| `events.handlerFailed` | An event handler threw, rejected or returned an Err | Fix the error shown with its stack. The handler keeps receiving later events. When an `onError` hook exists but did not receive the report, `fields.reportOutcome` says why: `queueFull`, `interrupted`, `clientClosed` or `subscriptionClosed` |
| `events.dropped` | A subscription queue was full, so an event was dropped. By default the oldest waiting event is dropped | Check `fields.limit`. For messages, raise `maxPendingMessages`. For bytes, raise `maxPendingBytes`. Handling events faster, raising `concurrency` when handlers can safely run together or accepting the drops also works |
| `events.overflow` | A subscription registered with the opt-in overflow `stop` ended because its queue was full | Keep the default `dropOldest`, or observe `waitForClose` and register again |
| `events.hookFailed` | The `onError` hook itself threw | Fix the hook. The original failure is logged right after it |
| `events.registeredAfterShutdown` | A handler, subscription or command router was registered after shutdown began, often from a handler still running at the time. It received an already-closed handle and never runs | Nothing during shutdown. At other times, register everything before stopping the client |
| `gateway.ignoredEventRegistered` | A handler is registered for an event whose dispatch types are all listed in `gateway.ignoredEvents` | Remove those types from `gateway.ignoredEvents`, or remove the handler. See [configuration](https://fluxerly.neontechspace.com/docs/configuration.md) |
| `gateway.dispatchRejected` | Fluxer sent an event the SDK could not validate, so it was skipped | Update the SDK. The record names the event type and failing field. Cached entries it could affect were cleared |
| `commands.rejected` and `commands.unmatched` (Debug) | A command guard, cooldown or argument rejected a message, or no command matched | With `runBot`, argument errors, active cooldowns and guards with a deny reason get a reply unless `onReject` is `"silent"`. A guard returning `false` sends nothing, even with the reply default. Add `onReject` to a router from `commands.create`, and `onUnmatched` where users need feedback for unknown commands, a group without a subcommand or a syntax mistake such as an unclosed quote |
| A rejected `SdkDefect` with code `sdk.defect` | An unexpected SDK or cleanup fault | Report it with the output of `describeError`. Code `application.defect` instead points at application code: The callback named in its cause, or a property getter on passed options or input that threw the cause |
Run with `FLUXERLY_DEBUG=1` to add Debug records for every area, or `FLUXERLY_DEBUG=rest,ratelimit` for selected ones. See [logging](https://fluxerly.neontechspace.com/docs/logging.md)
What happens to collectors registered after shutdown began
A `messages.collect` or `messages.collectReactions` call made after shutdown began returns a collector whose `result` fails with `ClientClosedError`, as for a collector that was already running when shutdown started. Registering middleware with `client.use` on a closing client still throws `ClientClosedError` in the default API, or dies with it in the Effect API. Invalid arguments remain misuse and throw `ConfigurationError` whatever the client state
## Node.js prints .env: not found
```text
node: .env: not found
```
Node.js could not open the file named after `--env-file`. Run the command from the bot's folder, and check that the file is named exactly `.env`. Some editors, such as Notepad, save it as `.env.txt`. Show file extensions in the file manager to spot that
## The process fails with a Node.js version error
```text
Error: Fluxerly needs Node.js 26.13 or newer, but this is Node.js 24.15.0. Install a current Node.js release from https://nodejs.org, then run the bot again
```
The SDK checks the Node.js version when it loads. Run `node --version` to see the version in use, or run `fluxerly doctor` (which still runs on older Node.js releases to report the mismatch alongside other setup checks), install a newer release, and open a new terminal so that it is found first
## The process fails with a require error
```text
Error: Fluxerly is ESM-only. Use import, and set "type": "module" in package.json (or use .mjs files)
```
The SDK ships only ECMAScript modules. Replace `require("@neontechspace/fluxerly")` with `import`, and either add `"type": "module"` to the project's `package.json` or name the file with `.mjs`. After that change, a `require` call left in any ES module fails with `require is not defined in ES module scope`, so replace each one with `import`
## TypeScript cannot find AbortSignal or AsyncDisposable
Install the Node.js types as a development dependency and include them, for example with `"types": ["node"]` in `tsconfig.json`. Handler signals are `AbortSignal` values and clients support `await using`, so the SDK's declarations use those Node.js types
```sh
npm install --save-dev @types/node
```
## No reply arrives
A bot that shows as online but does not answer usually has one of these problems. Check them in order:
1. The bot is running, and the message is from a person, not a bot. The starter answers the `!ping` command, with command names matched without regard to letter case
2. The bot can view the channel and send messages there
3. A command router uses the expected prefix, and the attached router is the one returned by the last `register` or `registerMany` call. Each call returns a new router, so attaching an earlier one misses later commands
4. No guard, cooldown or argument rejected the command. Rejected and unmatched commands are logged at Debug and counted in `diagnostics().counters`. With `runBot`, argument errors, active cooldowns and guards with a deny reason get an explanation unless `onReject` is `"silent"`. A guard returning `false` intentionally sends nothing. A router from `commands.create` sends these explanations only with `onReject: "reply"`, and `onUnmatched` answers unknown commands, a group typed without a subcommand and a syntax mistake such as an unclosed quote
5. The reply did not fail. The starter returns its reply, so a failed reply is logged as `commands.failed` with a message that tells local validation, provider rejection, timeout and delivery uncertainty apart
A callback that returns an `Err` result fails like one that throws, so its error reaches `onError` or the log. Handle an expected failure inside the callback when it should not count as a failure. See [commands](https://fluxerly.neontechspace.com/docs/commands.md) and [failure handling](https://fluxerly.neontechspace.com/docs/reliability.md)
## A webhook or OAuth call fails with HTTP 401
A [webhook or OAuth](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md) call can fail because Fluxer rejected a credential other than the bot token. The `hint` of the `WebhookOperationError` or `OAuthOperationError` then names the credential the request sent:
- Webhook token: Check the webhook ID and token, or recreate the webhook and use its new token
- OAuth client: Check the configured OAuth client ID and client secret
- User access token: Refresh it, or ask the user to authorize the application again
## A moderation action fails with HTTP 400
Suppose a kick, ban, timeout, role change or deletion of another person's message fails with HTTP 400 and [`errors.apiCode(error)`](https://fluxerly.neontechspace.com/docs/api/js-ts/errors/#errors) returns `"twoFactorRequired"`, although the bot holds the permission. The community requires two-factor authentication for moderation, and the account that owns the bot's application does not have it enabled. The community's `mfaLevel` is `GuildMfaLevels.Elevated` in such a community
Enable two-factor authentication on the account that owns the bot's application, then try again. Retrying without that change fails the same way. See [communities that require two-factor authentication](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#communities-that-require-two-factor-authentication)
## The gateway is connected but commands stopped
Look for `events.dropped` records and `diagnostics().counters.eventsDropped.overflow`, which show that events exceeded a handler's queue limits. A handler or middleware failure, including a synchronous throw, releases its handler slot and partition key without stopping the subscription. A full queue drops the oldest waiting event instead of stopping, or for a partitioned handler the oldest event of the longest backlog. Reading `diagnostics().counters.eventsDroppedByEvent` shows which events were dropped
Subscriptions that stop on overflow
A `client.on` subscription registered with `overflow: "stop"` closes when its queue is full, while the gateway stays connected. Observe its `waitForClose()` outcome. The [SDK runner](https://fluxerly.neontechspace.com/docs/starter-lifetime.md) watches its event subscriptions, its command router and the client connection. The `diagnostics().events` counters show registrations and running callbacks, but cannot tell whether a particular application task is working
## A request is slow
Enable Debug records for REST with `logging: { categories: { rest: "debug", ratelimit: "debug" } }` or `FLUXERLY_DEBUG=rest,ratelimit`. Each request prints its `requestId` (`#1` in colored output), method, route template, status, duration and attempt, and each rate-limit wait prints the same `requestId`, its route and delay so retries and waits correlate directly. Retries and waits are also counted in `diagnostics().counters`
Queues, deadlines and timeouts after sending
The `diagnostics().rest.queuedRequests` and `activeRequests` values show local queueing for this client. An operation deadline includes the wait in that queue, rate-limit waits, retries and HTTP work. The SDK then waits for its cleanup, so the Result can arrive after the deadline. A timeout after the request was sent does not prove that the write failed on Fluxer, so it is an [uncertain write](https://fluxerly.neontechspace.com/docs/glossary.md#uncertain-write). Do not replay it blindly
## The connection is recovering
Each `lifecycle.connectionLost` record names the reason and the next step, including the close code and its meaning when one is available. Transient recovery differs from terminal authentication or protocol rejection, which ends with `lifecycle.connectionEnded` and the error shown in full. The retained `run()` or `waitForClose()` outcome supplies the terminal result
Do not create another client or repeat `connect()` merely because the existing client is recovering. The client already owns that recovery lifetime. A closed client requires a new explicitly owned instance
## Shutdown is waiting, or application work finishes afterward
Check which work is still running. SDK shutdown waits for its own resources to close. It also waits for collector progress callbacks and native scoped [finalizers](https://fluxerly.neontechspace.com/docs/glossary.md#finalizer), so one of those that never finishes can hold up shutdown. The `lifecycle.shutdownComplete` record reports how long cleanup took, and each failed cleanup step is logged as `lifecycle.cleanupFailed`
Handlers are different. A stop requested through the `runBot` signal or a process signal, or a call to `client.shutdown({ drainMs })`, lets running handlers, scheduled tasks and their REST requests finish for a limited time, logged as `lifecycle.draining`, and then cancels what is left
A plain `client.shutdown()` cancels them at once. No shutdown waits for work a handler did not return, so database writes or detached Promises can finish after the subscription closes. Use [explicit application tracking](https://fluxerly.neontechspace.com/docs/application-supervision.md#drain-application-owned-work) when that work must settle before exit
Avoid `process.exit()` as a cleanup shortcut. Set `process.exitCode` after application cleanup instead. Neither cancellation nor a timeout proves rollback of an external mutation
## Keep diagnostics safe and useful
Record the SDK version from the `lifecycle.starting` record, the Node version, the record codes and the output of `describeError`. Alternatively, run `fluxerly triage --out triage.md`, `fluxerly triage --json` or pipe a log through `fluxerly triage --log - --print` to bundle redacted environment facts, static `doctor` checks and detected SDK codes automatically. The SDK masks tokens, Authorization headers, client secrets, invite codes and the user name and password in URLs in every record
Leave unsafe payload logging off when sharing logs. Application error messages and stacks still appear in ordinary logs, so redact message content from those errors too
---
# Send webhook messages and authorize users
Send messages through a webhook, including into threads and forum channels, and use the OAuth code grant with PKCE to get a user's consent
Fluxerly works with three kinds of credentials. A bot token runs the bot: It reads community resources and receives gateway events. A [webhook](https://fluxerly.neontechspace.com/docs/glossary.md#webhook) token lets an application post and manage that webhook's messages in its channel, without a bot. [OAuth](https://fluxerly.neontechspace.com/docs/glossary.md#oauth) lets an application ask a user for consent to access their account data
## Send through a configured webhook
A token-authenticated webhook is an incoming webhook, identified by `WebhookType.Incoming`
Store the incoming webhook ID and token in application configuration, like the bot token. Pass both to the helper, which creates a webhook client, sends one message and closes the client again
```ts
import { createWebhookClient, type WebhookClientOptions } from "@neontechspace/fluxerly"
export async function sendWebhookMessage(
credentials: WebhookClientOptions,
content: string,
) {
await using webhook = createWebhookClient(credentials)
return await webhook.send(content)
}
```
The `send` method takes a plain string for a text-only message, or an object with other fields such as `embeds`, and `editMessage` accepts the same forms to change a sent message. The send returns a [Result](https://fluxerly.neontechspace.com/docs/glossary.md#result) that holds the message Fluxer created on success
Mentions in webhook messages do not notify anyone unless `allowedMentions` allows them. The `await using` declaration shuts the client down when the helper returns or throws. For repeated sends, create one client per webhook, reuse it and shut it down when sending stops, as the [last section](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md#wire-it-up) shows
Follower webhooks and unknown kinds
A follower webhook has `WebhookType.ChannelFollower` and delivers [published announcements](https://fluxerly.neontechspace.com/docs/announcement-channels.md). It has no token, so `createWebhookClient` cannot use it. Bot clients can rename, move or delete it but cannot change its avatar. Handle `type: "unknown"` when reading a webhook kind this SDK version does not know
Failures, retries and credentials
Creating the client checks and copies the credentials locally without a request, and throws `ConfigurationError` if they are malformed. If a send fails with a `WebhookOperationError` whose `outcome` is `"unknown"`, Fluxer may already have posted the message, so check for it before sending again. The [reliability guide](https://fluxerly.neontechspace.com/docs/reliability.md) explains these uncertain writes
A send, reply or forward can supply `nonce` for best-effort duplicate suppression through the same webhook for five minutes. Use an application operation ID, not a new value for each attempt. Nonces do not guarantee exactly-once delivery, and omission sends no nonce. A forward can instead supply its nonce in `messageReference.source`, but supplying both locations fails before any request
A forward copies its source message, so it carries no new text, embeds, uploads or stickers. As in Fluxer, it may still carry null, empty or blank `content`, empty `embeds`, `attachments` and `stickerIds` lists, and null `stickerIds`, which the SDK sends as given. Other text, an embed, an upload or a sticker fails with reason `input` before any request
Webhook messages do not accept `tts`, and a send with it fails with reason `input` before any request. A rejected webhook token also logs one `rest.rejected` Warn record, even when the application handles the Result. The client prints Info and above to the console, and its `logging` option takes the same settings as a bot client's [logging](https://fluxerly.neontechspace.com/docs/logging.md)
Shutdown releases the SDK's copy of the credentials and ends its active requests. It does not delete the webhook on Fluxer, and the application must still protect its stored credentials
In an [Effect](https://fluxerly.neontechspace.com/docs/glossary.md#effect) application, a scope gives the webhook client the same lifetime. `Effect.scoped` shuts it down after success, failure or interruption
```ts
import { Effect } from "effect"
import { createWebhookClient } from "@neontechspace/fluxerly/effect"
export function sendWebhookMessageWithEffect(id: string, token: string, content: string) {
return Effect.scoped(
Effect.gen(function* () {
const webhook = yield* createWebhookClient({ id, token })
return yield* webhook.send(content)
}),
)
}
```
Keep this helper inside the application runtime shown in [the Effect bot guide](https://fluxerly.neontechspace.com/docs/effect-first-bot.md). The scope owns only this webhook client and leaves any bot client with its existing owner
Fluxer also accepts notifications from GitHub, Slack, Instatus and LibreDesk at the webhook's URL with `/github`, `/slack`, `/instatus` or `/libredesk` added, and turns them into messages. Those services post to that URL themselves, so set them up in the service. The SDK does not send them
## Post into threads and forum channels
A webhook posts into its own channel by default. To reach a [thread](https://fluxerly.neontechspace.com/docs/threads.md) of that channel, including a forum post, set `threadId` on the message. To start a new post in a forum or media channel instead, set `threadName`, and optionally `appliedTagIds`
```ts
import type { WebhookClient } from "@neontechspace/fluxerly"
export async function announceRelease(webhook: WebhookClient, version: string, tagIds: string[]) {
// The result is the first message of the new post, and its channelId is the post's ID
const first = await webhook.send({
content: `Release ${version} is out`,
threadName: `Release ${version}`,
appliedTagIds: tagIds,
})
if (first.isErr()) return first
return await webhook.send({ content: "Notes follow in this thread", threadId: first.value.channelId })
}
```
A webhook that belongs to a forum or media channel must use exactly one of `threadName` and `threadId` on every message, and Fluxer rejects a message with neither. A webhook in a text channel needs neither, and Fluxer rejects `threadName` there
The SDK checks the combinations that it can see before any request: A message cannot combine `threadName` and `threadId`, `appliedTagIds` needs `threadName`, and a reply or forward cannot start a post, because the new post holds no earlier message. A post takes at most five tags. Fluxer rejects an unknown tag, a `moderated` tag (a webhook cannot manage threads) and a post without a tag in a channel that requires one
The `fetchMessage`, `editMessage` and `deleteMessage` methods look in the webhook's channel unless their options carry the `threadId` of the thread that holds the message
```ts
import type { WebhookClient } from "@neontechspace/fluxerly"
export async function reviseThreadNote(webhook: WebhookClient, messageId: string, threadId: string) {
return await webhook.editMessage(messageId, "Notes moved to the wiki", { threadId })
}
```
Fluxer rejects a thread that belongs to another channel. The bot client's `rest.request` method refuses webhook token routes, so these options are the only way to reach a thread through a webhook
## Pick an OAuth method
Every step runs on the application server, which holds the client secret. The Effect API has the same methods
| I want to | Use |
| --- | --- |
| Create a client for the application's ID and secret | [`oauth.create`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauth-create) |
| Send a user to Fluxer's consent page | [`oauth.createState`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauth-createstate) and [`oauth.createPkce`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauth-createpkce), then [`authorizationUrl`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-authorizationurl) |
| Turn the callback's code into tokens | [`exchangeCode`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-exchangecode) |
| Get a new token pair before the access token expires | [`refresh`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-refresh) |
| End a user's tokens for the application | [`revoke`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-revoke) |
| Read who the user is | [`fetchIdentity`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-fetchidentity) |
| Check what a stored access token allows, without the client secret | [`fetchAuthorization`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-fetchauthorization) |
| List the user's communities | [`fetchGuilds`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-fetchguilds) |
| List the user's connected accounts | [`fetchConnections`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-fetchconnections) |
| Check whether a token is still active, with the client secret | [`introspect`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-introspect) |
| Read one community, its roles or another delegated user route | [`request`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-request), as [reading with a user token](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md#reading-with-a-user-token) shows |
| Stop the client and release its copy of the secret | [`shutdown`](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient-shutdown), or `await using` |
## Create a user-consent URL
OAuth sends a user to Fluxer to approve access, then back to the application's registered redirect URI with a one-use code
The application needs its client secret stored on the server, the exact registered redirect URI, an unpredictable `state` value that ties the callback to this request, and a fresh PKCE verifier and challenge, which prove that the same server finishes the exchange. Store the state and verifier together in a one-use server record before sending the user to the consent URL
The redirect URI uses HTTPS, or HTTP for a loopback host or an IP address such as a LAN address. The SDK handles it as Fluxer does: It removes U+000C and U+202E and trims surrounding whitespace, then sends that text in the consent URL, which Fluxer compares exactly with the registered redirect URIs. The code exchange sends the URL's standard form, such as `https://example.test/` for `https://example.test`, because Fluxer keeps that form with the code
```ts
import { oauth, OAuthScopes, type OAuthConfig } from "@neontechspace/fluxerly"
export async function prepareOAuthAuthorization(
config: OAuthConfig,
redirectUri: string,
state: string,
) {
await using client = oauth.create(config)
const pkce = oauth.createPkce()
const authorization = await client.authorizationUrl({
redirectUri,
scopes: [OAuthScopes.Identify],
state,
codeChallenge: pkce.challenge,
})
return authorization.map((url) => ({ url, codeVerifier: pkce.verifier }))
}
```
The web server redirects the user's browser to the returned URL and keeps the returned verifier with the matching state. Never put the verifier or client secret in the URL, browser code or logs. Request scopes with the `OAuthScopes` constants
Asking to add the bot through OAuth
Adding `OAuthScopes.Bot` to the scopes asks the user to add the bot through the consent flow. Fluxer's consent flow decides where the bot is added, and community, channel and permission values in the URL are only suggestions
## Validate the callback before exchanging its code
When Fluxer redirects the user back, the callback handler compares the returned state with the unused record from the previous step. Only on a match, consume that record and exchange the callback's code, using the original verifier and the same redirect URI from the record. Pass it as it was passed to `authorizationUrl`, and the SDK sends the standard form that Fluxer kept with the code
```ts
import { oauth, type OAuthConfig } from "@neontechspace/fluxerly"
export async function exchangeValidatedOAuthCode(
config: OAuthConfig,
redirectUri: string,
code: string,
codeVerifier: string,
) {
await using client = oauth.create(config)
return await client.exchangeCode({
code,
redirectUri,
codeVerifier,
})
}
```
A successful exchange returns a token pair. Store it in the application's protected token store. The granted scopes can differ from the requested ones
Refreshes and failed exchanges
Coordinate refreshes and replace the stored token pair as a whole, because a successful refresh can also replace the refresh token.
An exchange code works once. A timeout, cancellation or lost response after the request was sent can leave the outcome unknown, because Fluxer may have used the code. Start a new consent flow instead of repeating that exchange
A rejected client ID or secret also logs one `rest.rejected` Warn record, while a rejected user access token is only returned, because it concerns one user. The OAuth client accepts the same `logging` option as a bot client. At Debug, each OAuth request logs one `rest.request` record with its method, route, status and duration, never its query, form, body or `Authorization` value
To check a stored access token without the client secret, `fetchAuthorization` reads what the user authorized: The application, the granted scopes, when the token expires and, with the `identify` scope, the user. A rejected, expired or revoked token fails with reason `rejected` and HTTP 401
The `fetchIdentity`, `fetchAuthorization`, `fetchGuilds`, `fetchConnections` and `introspect` methods are reads. Their failures set `details.read`, so `errors.isRetryable` can identify a transient failure without implying that tokens changed. OAuth requests are never retried automatically. Exchange, refresh and revoke requests with an unknown outcome remain unsafe to repeat. Discovery and OAuth transport failures retain only sanitized causes, including a safe transport code such as `ECONNRESET` when available, not the original error text
The default API returns expected webhook and OAuth failures as `Result` values. Handle an `Err` where the helper is called, for example by logging `describeError(result.error)`, and never log the webhook token, client secret or verifier. Operation details are in the [webhook client reference](https://fluxerly.neontechspace.com/docs/api/js-ts/invites-and-webhooks/#webhookclient) and the [OAuth client reference](https://fluxerly.neontechspace.com/docs/api/js-ts/oauth/#oauthclient)
Revoking a token revokes every access and refresh token for that user and application, so the user's other sessions with the application stop working too
### Reading with a user token
The dedicated OAuth helpers cover identity, authorization metadata, guild lists and connections. For another delegated user route such as `GET /guilds/{guild_id}`, `GET /guilds/{guild_id}/roles` or `GET /users/@me`, call `client.request(accessToken, { method: "GET", path })` on the OAuth client instead of `client.rest.request`, which always sends the bot token
The `request` method reuses the OAuth client's instance discovery, concurrency limit, timeout, 1 MiB response cap and secret masking without retaining or logging the access token. Community routes need the `guilds` scope, and the current-user route needs `identify`, plus `email` for email fields
Check the returned status and validate the body before relying on it, since the SDK neither decodes custom route payloads nor retries OAuth requests. Keep the access token out of logs, error messages and URLs
## Wire it up
A webhook client lives beside `runBot`, not inside it. Create it once before starting the bot, use it from commands or handlers, and let `await using` shut it down after the bot stops. This bot posts `!announce ` through the webhook for members who can manage webhooks in the webhook's channel. The permission guard checks the channel of the incoming message, so the second guard accepts the command only in that channel
```ts
import { createWebhookClient, guards, runBot } from "@neontechspace/fluxerly"
const id = process.env.FLUXER_WEBHOOK_ID
const token = process.env.FLUXER_WEBHOOK_TOKEN
if (!id || !token) throw new Error("Set FLUXER_WEBHOOK_ID and FLUXER_WEBHOOK_TOKEN")
await using webhook = createWebhookClient({ id, token })
await runBot({
token: process.env.FLUXER_BOT_TOKEN,
commands: {
prefix: "!",
commands: {
announce: {
description: "Post an announcement through the webhook",
guard: [
guards.requirePermissions(["ManageWebhooks"]),
async ({ message, signal }) => {
const target = await webhook.fetch({ signal })
if (target.isErr()) throw target.error
const inChannel = message.channelId === target.value.channelId
return inChannel || { deny: "Send this command in the webhook's channel" }
},
],
arguments: { text: { type: "text", rest: true } },
execute: async ({ values, reply, signal }) => {
const posted = await webhook.send(values.text, { signal })
return posted.isErr() ? posted : reply("Announcement posted")
},
},
},
},
})
```
OAuth does not belong in the bot runner. The consent redirect and the callback are web requests, so the OAuth helpers run in the application's web server, which can be a separate process from the bot. Create the OAuth client there, and pass anything the bot needs to know through the application's own storage
---
# Where do I…?
Find the guide or API for a common bot task
Find a task below and follow its link to the guide section or reference page that covers it. Unfamiliar terms are defined in the [glossary](https://fluxerly.neontechspace.com/docs/glossary.md)
## Start
- [Create a Fluxer application and get its token](https://fluxerly.neontechspace.com/docs/create-a-bot.md)
- [Add the bot to a community](https://fluxerly.neontechspace.com/docs/create-a-bot.md#3-invite-the-bot-to-a-community)
- [Run a first bot that answers !ping](https://fluxerly.neontechspace.com/docs/quick-start.md)
- [Build a bot with commands, a welcome message and clean shutdown](https://fluxerly.neontechspace.com/docs/small-bot.md)
- [Understand clients, events, Results and caches](https://fluxerly.neontechspace.com/docs/core-concepts.md)
- [Run code when the bot is connected](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#run-code-once-the-bot-is-connected)
- [Copy a complete example bot](https://fluxerly.neontechspace.com/docs/examples.md)
## Messages
- [Reply to a message and check the result](https://fluxerly.neontechspace.com/docs/messages.md#reply-to-a-message-and-check-what-happened)
- [Mention a user or role safely](https://fluxerly.neontechspace.com/docs/messages.md#mention-someone-deliberately)
- [Edit a sent message](https://fluxerly.neontechspace.com/docs/messages.md#send-then-edit-the-returned-message)
- [Send an embed](https://fluxerly.neontechspace.com/docs/messages.md#build-an-embed)
- [Attach or download a file](https://fluxerly.neontechspace.com/docs/messages.md#upload-a-small-generated-file)
- [Send a direct message](https://fluxerly.neontechspace.com/docs/messages.md#send-a-requested-direct-message)
- [Send a voice note](https://fluxerly.neontechspace.com/docs/messages.md#mark-media-as-explicit-or-send-a-voice-note)
- [Start a thread in a channel](https://fluxerly.neontechspace.com/docs/threads.md#create-a-thread)
- [Start a post in a forum channel](https://fluxerly.neontechspace.com/docs/forum-channels.md#start-posts)
- [Publish a message in an announcement channel](https://fluxerly.neontechspace.com/docs/announcement-channels.md#send-a-message-then-publish-it)
- [Add a reaction to a message](https://fluxerly.neontechspace.com/docs/emoji-and-stickers.md#find-an-emoji-and-use-it-twice)
- [Delete a message](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-delete)
- [Clear recent messages in a channel](https://fluxerly.neontechspace.com/docs/examples.md#moderation-commands)
- [Use custom emoji and stickers](https://fluxerly.neontechspace.com/docs/emoji-and-stickers.md)
- [Post through a webhook without a bot connection](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md#send-through-a-configured-webhook)
- [Look up every message method](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages)
## Commands
- [Register prefix commands](https://fluxerly.neontechspace.com/docs/commands.md#register-commands)
- [Parse command arguments](https://fluxerly.neontechspace.com/docs/commands.md#convert-arguments-before-execution)
- [Restrict a command with guards, cooldowns or middleware](https://fluxerly.neontechspace.com/docs/commands.md#guard-limit-and-wrap-commands)
- [Generate a help command](https://fluxerly.neontechspace.com/docs/commands.md#add-help-from-the-registered-commands)
- [Configure commands in runBot](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#runbot)
- [Look up the built-in guards](https://fluxerly.neontechspace.com/docs/api/js-ts/commands/#guards)
## Events
- [Welcome new members](https://fluxerly.neontechspace.com/docs/examples.md#welcome-messages)
- [Wait for one future event](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#wait-for-one-future-event)
- [Ask a question and collect the reply](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#ask-a-question-without-missing-a-fast-reply)
- [Collect reactions](https://fluxerly.neontechspace.com/docs/events-and-collectors.md#accept-a-confirmation-reaction)
- [Check whether one user reacted](https://fluxerly.neontechspace.com/docs/api/js-ts/messages/#messages-fetchhasreaction)
- [Run code around every handler](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#use)
- [Look up the handler registration options](https://fluxerly.neontechspace.com/docs/api/js-ts/client/#on)
## Communities and permissions
- [Read a community and its members](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#read-a-community-and-one-member-together)
- [Check permissions](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#check-permissions-using-available-data)
- [Check whether the bot or a moderator outranks a member](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#members-fetchcanmanage)
- [Give a member a role](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#grant-a-configured-opt-in-role)
- [Give a role an icon](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#give-a-role-an-icon)
- [Kick, ban or time out a member](https://fluxerly.neontechspace.com/docs/guilds-and-permissions.md#moderate-members)
- [Look up member and role methods](https://fluxerly.neontechspace.com/docs/api/js-ts/guilds-and-members/#members)
## Data and cache
- [Search or scan message history](https://fluxerly.neontechspace.com/docs/history-and-cache.md)
- [Turn on and size the caches](https://fluxerly.neontechspace.com/docs/configuration.md#cache)
- [Read from the cache and fetch when data is missing](https://fluxerly.neontechspace.com/docs/history-and-cache.md#use-the-cache-then-fetch-if-needed)
- [Call a Fluxer API route that has no SDK method](https://fluxerly.neontechspace.com/docs/api/endpoints/)
- [Ask for a person's consent with OAuth](https://fluxerly.neontechspace.com/docs/webhooks-and-oauth.md#create-a-user-consent-url)
- [Keep data across restarts](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#keep-reminders-across-restarts)
## Production
- [Choose client options](https://fluxerly.neontechspace.com/docs/configuration.md)
- [Read and configure log output](https://fluxerly.neontechspace.com/docs/logging.md)
- [Set the bot's status](https://fluxerly.neontechspace.com/docs/api/js-ts/client-and-lifecycle/#presence-set)
- [Schedule a task or reminder](https://fluxerly.neontechspace.com/docs/starter-lifetime.md#run-work-later-or-on-a-schedule)
- [Handle failures that have no Result](https://fluxerly.neontechspace.com/docs/reliability.md#report-failures-that-have-no-result)
- [Retry a failed request safely](https://fluxerly.neontechspace.com/docs/reliability.md#send-once-when-the-outcome-is-uncertain)
- [Stop the bot cleanly](https://fluxerly.neontechspace.com/docs/starter-lifetime.md)
- [Deploy the bot](https://fluxerly.neontechspace.com/docs/deploying.md)
- [Split a large bot into shards](https://fluxerly.neontechspace.com/docs/sharding.md)
- [Watch subscriptions and finish application work before exit](https://fluxerly.neontechspace.com/docs/application-supervision.md)
- [Look up every client option](https://fluxerly.neontechspace.com/docs/api/js-ts/options/#clientoptions)
## Testing
- [Test a bot without Fluxer](https://fluxerly.neontechspace.com/docs/testing.md)
- [Test a runBot bot with its own options](https://fluxerly.neontechspace.com/docs/testing.md#share-the-bots-options-with-its-tests)
- [Test handlers registered with client.on](https://fluxerly.neontechspace.com/docs/testing.md#test-handlers-registered-with-clienton)
- [Look up the test client](https://fluxerly.neontechspace.com/docs/api/testing/)
## Effect
- [Write a first bot with Effect](https://fluxerly.neontechspace.com/docs/effect-first-bot.md)
- [Handle failures, collect replies and run reads together](https://fluxerly.neontechspace.com/docs/effect-workflows.md)
- [Provide the client as a service and test with Layers](https://fluxerly.neontechspace.com/docs/effect-application-testing.md)
- [Test a native runBot bot against an in-memory Fluxer](https://fluxerly.neontechspace.com/docs/effect-application-testing.md#test-a-runbot-bot-against-an-in-memory-fluxer)
- [Look up the Effect entry point](https://fluxerly.neontechspace.com/docs/api/effect/)
- [Look up the Effect test client](https://fluxerly.neontechspace.com/docs/api/effect-testing/)
## Help
- [Check project setup offline with fluxerly doctor](https://fluxerly.neontechspace.com/docs/cli.md#check-setup-offline-with-doctor)
- [Investigate a bug with fluxerly triage](https://fluxerly.neontechspace.com/docs/cli.md#investigate-failures-with-triage)
- [Match a log line with its fix](https://fluxerly.neontechspace.com/docs/troubleshooting.md#match-a-log-line-with-its-fix)
- [Look up an error or log code](https://fluxerly.neontechspace.com/docs/codes/)
- [Find out why the bot does not reply](https://fluxerly.neontechspace.com/docs/troubleshooting.md#no-reply-arrives)
- [Read short answers to common questions](https://fluxerly.neontechspace.com/docs/faq.md)
- [Look up a term](https://fluxerly.neontechspace.com/docs/glossary.md)
- [Check Node.js, TypeScript and Effect requirements](https://fluxerly.neontechspace.com/docs/support-and-compatibility.md)
- [Get help or report a vulnerability](https://fluxerly.neontechspace.com/docs/support-and-compatibility.md#get-help)
- [Browse the API reference by task](https://fluxerly.neontechspace.com/docs/api/tasks/)