Skip to content

Configuration

createShardlens(client, options) attaches Shardlens to a discord.js client. Call it before client.login(). Sending to a collector needs only endpoint and apiKey; with exporters only, leave both out.

bot.ts
import { createShardlens } from '@shardlens/discordjs';
import { Client, GatewayIntentBits } from 'discord.js';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
export const lens = createShardlens(client, {
endpoint: process.env.SHARDLENS_URL!,
apiKey: process.env.SHARDLENS_INGEST_KEY!,
environment: process.env.NODE_ENV === 'production' ? 'production' : 'staging',
release: process.env.npm_package_version, // compare versions on the dashboard
captureOptionValues: ['language', 'difficulty'], // only these options' values are recorded
sampleRate: { gauge_window: 0.5 }, // very large bots only; counts are re-weighted
disable: ['process'], // skip CPU and memory gauges
});

This table is generated from the SDK’s source, so it always matches the version these docs were built from.

OptionTypeDescription
endpointstringYour collector's URL, for example https://stats.example.com. HTTPS, or HTTP to localhost only. Leave out with apiKey to run with exporters only.
apiKeystringIngest-only API key (slk_ingest_…).
exportersreadonly ShardlensExporter[]In-process metrics exporters, such as prometheusExporter() from @shardlens/exporter-prometheus. They get every event before sampling, never with a user. Works with or without a collector.
mode'privacy' | 'audit'Whether users are hashed or identified. 'privacy' (default): user IDs are hashed in-process and never leave the bot. 'audit': also sends who ran each interaction (user ID, username and avatar), encrypted at rest; only takes effect when the collector is in audit mode too. See the audit-mode guide before turning it on.
auditIncludeProfilebooleanAudit mode only: send each user's username and avatar with their ID. Default true; false records IDs only. Nothing else about a user is ever collected.
saltPeriodSaltPeriodHas no effect: the collector decides the salt period (dashboard **Settings → User identity**), and the SDK hashes with the salts it is given. Still accepted so configurations that set it keep working.
maxQueueSizenumberMemory ceiling, in events. Default 10,000.
flushIntervalMsnumberFlush interval. Default 5,000 ms.
maxBatchSizenumberEvents per batch (max 499 plus one health event). Default 499.
captureOptionValuesreadonly string[]Option names whose values may be recorded, for slash commands and for the optionValues you pass with message commands. Values of user, channel, role, mentionable and attachment options, and any value holding a Discord ID, are never recorded; strings are cut to 100 characters. Default none.
normaliseCustomId((customId: string) => string)Replaces the default custom-ID normaliser (numbers and IDs become *).
sampleRateReadonly<Record<string, number>>Sample rate per event type in (0, 1], for very large bots, such as { gauge_window: 0.5 }. Counts are re-weighted. Rates below 1/10,000 are raised to 1/10,000, the most one kept event can stand for.
environmentstringSeparates staging from production. Default 'production'.
releasestringYour bot's version, to compare releases.
dryRunbooleanPrint events to the console instead of sending them.
disablereadonly MetricGroup[]Turn off whole metric groups. 'interactions' also turns off message (prefix) commands.
loggerLoggerWhere SDK warnings go. Default console.
optedOutIterable<string | bigint>Users who opted out earlier (for example loaded from your database). Their events are dropped in-process. BigInt IDs, as some database clients return them, are accepted.
onOptOutChange((userId: string, optedOut: boolean) => void)Called when a user opts out or back in, so you can persist the choice. It may be async: if it throws or its promise rejects, the failure is counted (see lens.on('error')), never thrown into your bot.
spool{ dir: string; maxBytes?: number | undefined }Keep events on disk during long collector outages and across restarts: { dir: './shardlens-spool' }. Used when memory is half full while the collector is unreachable, and on shutdown() for anything unsent; replayed first when the collector is back. Capped at maxBytes (default 100 MB): at the cap the oldest batches are dropped first, and counted in stats().dropped.spool_evicted. Files hold hashed events only, never user IDs or audit-mode identities. Default: off (memory only).
refreshGuildCountsbooleanRefresh each server's approximate member count with GET /guilds/{id}?with_counts=true, one server every two seconds (30 a minute, on your bot's REST budget), instead of only at startup and join. Presence counts are never read. Default false.
fetchtypeof fetchOverride fetch (tests, proxies).

mode?: 'privacy' | 'audit'

Whether users are hashed or identified. 'privacy' (default): user IDs are hashed in-process and never leave the bot. 'audit': also sends who ran each interaction (user ID, username and avatar), encrypted at rest; only takes effect when the collector is in audit mode too. See the audit-mode guide before turning it on.

Audit mode has to be switched on in the collector as well, and it changes what you have to tell your users. Read the audit mode guide first.

captureOptionValues?: readonly string[]

Option names whose values may be recorded, for slash commands and for the optionValues you pass with message commands. Values of user, channel, role, mentionable and attachment options, and any value holding a Discord ID, are never recorded; strings are cut to 100 characters. Default none.

By default Shardlens records which options were used, never what was typed. Allow-list options whose values are safe and useful (a language, a difficulty) and never free-text options. User, channel, role, mentionable and attachment options are never recorded even when allow-listed, nor is any value holding a Discord ID, which a user can type. Values are passed through secret redaction and cut to 100 characters before they are sent.

normaliseCustomId?: ((customId: string) => string)

Replaces the default custom-ID normaliser (numbers and IDs become *).

Buttons, select menus and modals are grouped by custom ID. The default normaliser turns IDs and numbers into *, so ticket:close:112233445566778899 becomes ticket:close:*. Secrets are redacted before normalising, and the result is cut to 100 characters.

sampleRate?: Readonly<Record<string, number>>

Sample rate per event type in (0, 1], for very large bots, such as { gauge_window: 0.5 }. Counts are re-weighted. Rates below 1/10,000 are raised to 1/10,000, the most one kept event can stand for.

Only very large bots need this. A sampled event carries its weight, so totals on the dashboard stay correct.

optedOut?: Iterable<string | bigint>

Users who opted out earlier (for example loaded from your database). Their events are dropped in-process. BigInt IDs, as some database clients return them, are accepted.

onOptOutChange?: ((userId: string, optedOut: boolean) => void)

Called when a user opts out or back in, so you can persist the choice. It may be async: if it throws or its promise rejects, the failure is counted (see lens.on('error')), never thrown into your bot.

See the /privacy command for a complete example.

spool?: { dir: string; maxBytes?: number | undefined }

Keep events on disk during long collector outages and across restarts: { dir: './shardlens-spool' }. Used when memory is half full while the collector is unreachable, and on shutdown() for anything unsent; replayed first when the collector is back. Capped at maxBytes (default 100 MB): at the cap the oldest batches are dropped first, and counted in stats().dropped.spool_evicted. Files hold hashed events only, never user IDs or audit-mode identities. Default: off (memory only).

Without a spool, events wait in memory (10,000 by default) while the collector is unreachable, and the least important are dropped first once that fills up. With spool: { dir: './shardlens-spool' }, they move to disk instead:

  • During an outage, as soon as memory is half full, and on shutdown() for anything still unsent, so events also survive a restart.
  • When the collector answers again, spooled batches are sent first, oldest first, and deleted only once accepted. The collector ignores events it already has, so a replay never counts anything twice.
  • Spool files hold hashed events only. User IDs, and audit-mode identities, are never written to disk.
  • The shards of one bot can share the folder: maxBytes caps the folder, and any of them replays what is there.
  • At the cap, the oldest batches are deleted to make room. Those events are lost, and counted in lens.stats().dropped.spool_evicted.
  • Erasing a user (forgetUser, /privacy erase) also removes their events from the spool.

refreshGuildCounts?: boolean

Refresh each server's approximate member count with GET /guilds/{id}?with_counts=true, one server every two seconds (30 a minute, on your bot's REST budget), instead of only at startup and join. Presence counts are never read. Default false.

Without the GuildMembers intent, discord.js only learns a server’s member count when the bot starts or joins it. This refresh keeps the counts current at a gentle, fixed pace.

The SDK never installs signal handlers. Call shutdown() on your own shutdown path to send what is queued:

import type { Shardlens } from '@shardlens/discordjs';
import type { Client } from 'discord.js';
declare const client: Client;
declare const lens: Shardlens;
// The SDK never installs signal handlers. Flush on your own shutdown path.
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.once(signal, async () => {
await lens.shutdown({ timeoutMs: 2_000 }); // gives up after 2 s; never throws
await client.destroy();
process.exit(0);
});
}

Calling shutdown() again, as the second of two signals does, waits for the same flush. With a ShardingManager or discord-hybrid-sharding, the manager must also pass signals on to its processes: see Stopping a sharded bot.