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.
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});All options
Section titled “All options”This table is generated from the SDK’s source, so it always matches the version these docs were built from.
| Option | Type | Description |
|---|---|---|
endpoint | string | Your collector's URL, for example https://stats.example.com. HTTPS, or HTTP to localhost only. Leave out with apiKey to run with exporters only. |
apiKey | string | Ingest-only API key (slk_ingest_…). |
exporters | readonly 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. |
auditIncludeProfile | boolean | Audit 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. |
saltPeriod | SaltPeriod | Has 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. |
maxQueueSize | number | Memory ceiling, in events. Default 10,000. |
flushIntervalMs | number | Flush interval. Default 5,000 ms. |
maxBatchSize | number | Events per batch (max 499 plus one health event). Default 499. |
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. |
normaliseCustomId | ((customId: string) => string) | Replaces the default custom-ID normaliser (numbers and IDs become *). |
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. |
environment | string | Separates staging from production. Default 'production'. |
release | string | Your bot's version, to compare releases. |
dryRun | boolean | Print events to the console instead of sending them. |
disable | readonly MetricGroup[] | Turn off whole metric groups. 'interactions' also turns off message (prefix) commands. |
logger | Logger | Where SDK warnings go. Default console. |
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. |
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). |
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. |
fetch | typeof fetch | Override fetch (tests, proxies). |
Options worth knowing
Section titled “Options worth knowing”Hashed or identified users
Section titled “Hashed or identified users”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.
Option values
Section titled “Option values”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.
Custom IDs
Section titled “Custom IDs”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.
Sampling
Section titled “Sampling”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.
Opt-outs
Section titled “Opt-outs”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.
Disk spool
Section titled “Disk spool”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:
maxBytescaps 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.
Member counts
Section titled “Member counts”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.
Shutting down
Section titled “Shutting down”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.