SWAGcommands
Guides

Features

Run setup tasks once or schedule recurring work.

Features are jobs that run at a startup phase, optionally on a timer. Put one default-exported function or object in each file under featuresDir.

src/features/hello.ts
import type { FeatureFunction } from "swagcommands";

const hello: FeatureFunction = ({ client }) => {
  console.log(`Hello from ${client.user?.tag}`);
};

export default hello;

A plain function runs once at FeaturePhase.ClientReady. To choose a phase or add a cleanup function, use an object:

import { FeaturePhase } from "swagcommands";
import type { Feature } from "swagcommands";

const commandIndex = {
  phase: FeaturePhase.AfterCommands,
  run: ({ instance }) => {
    const names = instance.listCommands().map((item) => item.name);
    console.log(names);
    return () => console.log("Command index cleanup");
  },
} satisfies Feature;

export default commandIndex;
PhaseWhen it runs
BeforeCommandsInside SWAG.create(), before command loading
AfterCommandsInside SWAG.create(), after command loading
ClientReadyThrough startFeatures(), after Discord is ready

Repeat on a timer

import { FeaturePhase } from "swagcommands";
import type { Feature } from "swagcommands";

const guildCount = {
  phase: FeaturePhase.ClientReady,
  everyMs: 5 * 60_000,
  runOnStart: true,
  run: async ({ client, signal }) => {
    if (signal.aborted) return;
    console.log(`Guilds: ${client.guilds.cache.size}`);
  },
} satisfies Feature;

export default guildCount;

runOnStart fires the first run immediately; otherwise the first run waits one interval. A feature's next interval starts after its current run finishes, so the same feature doesn't overlap itself. Recurring runs cannot return cleanup functions; use the abort signal and stopFeatures() instead. An individual recurring failure goes to onError and later runs continue.

Feature names default to their relative paths (without extension), or you can set name. They must be unique. Files are discovered recursively; imported top-level code runs during SWAG.create() even for a ClientReady feature. Call await swag.stopFeatures() on shutdown. It clears timers, signals jobs, waits for in-flight runs, and executes one-time cleanup in reverse order.

On this page