This is the full developer documentation for Shardlens # Choose your setup > Use the Shardlens dashboard, a dashboard of your own, or none. Every number can be read through the package either way. The SDK in your bot is the same in every setup: it sends events to a collector, which stores and counts them. What you choose is where you look at the numbers. You can change your mind later without losing anything. | You want | Set it up with | You read the numbers | | ---------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------- | | The Shardlens dashboard | `npx shardlens init …` | At your collector’s address, in a browser | | A dashboard you already have | `npx shardlens init … --dashboard own` | In your own pages, through [`@shardlens/client`](../../guides/your-own-dashboard/) | | No dashboard | `npx shardlens init … --dashboard none` | From scripts, in Discord, in your own database or in Grafana | | No collector at all | Nothing to run | In Prometheus or OpenTelemetry only ([exporter only](../../self-hosting/exporter-only/)) | `…` stands for `--domain stats.example.com --app-id 123456789012345678`, as in the [quick start](../quick-start/). ## The Shardlens dashboard [Section titled “The Shardlens dashboard”](#the-shardlens-dashboard) The default. The collector serves the dashboard at its own address: follow the [quick start](../quick-start/). ## A dashboard you already have [Section titled “A dashboard you already have”](#a-dashboard-you-already-have) The collector runs as an API only, and your dashboard’s server asks it for what your pages show. ```sh npx shardlens init --domain stats.example.com --app-id 123456789012345678 --dashboard own ``` Besides the collector’s files, this writes `dashboard.env`: the collector’s address and a read key, for your dashboard’s server. There, install `@shardlens/client` and ask for any number the Shardlens dashboard would show: [Use your own dashboard](../../guides/your-own-dashboard/) has the code. To show **who ran what** in your own pages, add `--identify-users`. It turns on [audit mode](../../guides/audit-mode/) in the collector and adds an activity key to `dashboard.env`, which reads the activity log the way a Discord sign-in does in the Shardlens dashboard. Audit mode is two-sided: give your bot’s `createShardlens` `mode: 'audit'` as well, or it keeps sending hashed users and the log stays empty. ## No dashboard [Section titled “No dashboard”](#no-dashboard) The collector still stores and counts everything; there is no page to open. ```sh npx shardlens init --domain stats.example.com --app-id 123456789012345678 --dashboard none ``` You can still get at every number: * **From a script**, with `@shardlens/client`, the read key in `.env` and the collector’s address (`SHARDLENS_PUBLIC_URL` in `.env`) as `SHARDLENS_URL`: this-week.ts ```ts // Run by hand or on a schedule: this week's commands, without a dashboard. import { createShardlensClient, lastDays } from '@shardlens/client'; const shardlens = createShardlensClient({ endpoint: process.env.SHARDLENS_URL!, // https://stats.example.com apiKey: process.env.SHARDLENS_READ_KEY!, // slk_read_… }); const { rows } = await shardlens.commands({ range: lastDays(7) }); for (const row of rows.slice(0, 10)) { console.log(`${row.command}: ${row.runs} runs, p95 ${row.p95Ms === null ? '?' : Math.round(row.p95Ms)} ms`); } ``` * **In your own database:** set `SHARDLENS_SINK_URL` and every event is [copied there](../../self-hosting/your-own-database/) as it arrives. * **In Grafana:** the [Prometheus and OpenTelemetry exporters](../../guides/grafana/) send bot health to the monitoring you already run. * **In Discord:** [scheduled reports](../../guides/reports/) and [alerts](../../guides/alerts/) post to a channel. They are set up in the Shardlens dashboard, so turn it on for that (below); once set up they keep running with it off. ## Inside your bot (embedded mode) [Section titled “Inside your bot (embedded mode)”](#inside-your-bot-embedded-mode) [Embedded mode](../../self-hosting/embedded/) makes the same choice with one option: `dashboard: false` starts the collector without its pages, and `collector.readKey` is the key `@shardlens/client` needs. ## What the package can read [Section titled “What the package can read”](#what-the-package-can-read) Everything the Shardlens dashboard shows is an answer from the collector’s API, and `@shardlens/client` asks for the same answers. Nothing is kept for the dashboard alone. | Data | Key it needs | In `@shardlens/client` | | ------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------- | | Every chart and table: commands, servers, growth, audience, reliability, premium, custom events, funnels, retention | Read key | One method per query, such as `commands()`, `command()`, `servers()`, `reliability()` | | The live tiles (runs per minute, response time, shards) | Read key | `live()` | | Who ran what, in [audit mode](../../guides/audit-mode/) | Activity key | `activity.log()` and `activity.topUsers()` | What stays in the Shardlens dashboard is changing things, which needs a person signed in with Discord: settings, alerts, reports, API keys, erasing a user and the CSV export of the activity log. Keys stay on a server A read key can read every number, and an activity key can read who ran what. Use them from your dashboard’s server or a script, never from code that runs in a browser. ## Changing your mind [Section titled “Changing your mind”](#changing-your-mind) The choice is one line in the collector’s `.env`: ```sh SHARDLENS_DASHBOARD=on # or off ``` Change it and restart the collector (`docker compose up -d`), or run `init` again with `--force` and the choice you want: `npx shardlens init … --force --dashboard shardlens`. Your data, keys and settings stay as they are, and so does `SHARDLENS_MODE` if `--identify-users` wrote it: while it is set, Settings shows the mode but can’t change it, so remove the line to choose the mode there again. # Configuration > Every option createShardlens accepts. `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](../../self-hosting/exporter-only/), leave both out. bot.ts ```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 }); ``` ## All options [Section titled “All options”](#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>` | 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` | 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”](#options-worth-knowing) ### Hashed or identified users [Section titled “Hashed or identified users”](#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](../../guides/audit-mode/) first. ### Option values [Section titled “Option values”](#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”](#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”](#sampling) `sampleRate?: Readonly>` 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”](#opt-outs) `optedOut?: Iterable` 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](../../guides/privacy-command/) for a complete example. ### Disk spool [Section titled “Disk spool”](#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: `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. ### Member counts [Section titled “Member counts”](#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”](#shutting-down) The SDK never installs signal handlers. Call `shutdown()` on your own shutdown path to send what is queued: ```ts 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](../../guides/sharding/#stopping-a-sharded-bot). Tip Use `dryRun: true` while developing to print events to the console instead of sending them. # Install with an AI agent > Paste one prompt into Claude Code, Cursor, Copilot or Codex and let it add Shardlens to your bot. Open your bot’s repository in a coding agent (Claude Code, Cursor, GitHub Copilot, Codex, Windsurf or similar), paste the prompt below and let it work. It installs `@shardlens/discordjs`, creates Shardlens next to your client, wraps your interaction handler, records prefix commands if you have them, flushes on shutdown (in the manager too, for a sharded bot) and documents the two settings. It works out your setup first: TypeScript or JavaScript, ESM or CommonJS, the discord.js guide layout, a framework such as Sapphire or discordx or a handler of your own, and single-process bots, `ShardingManager`, internal sharding or discord-hybrid-sharding. Ask for embedded mode in the same message if you want the collector inside your bot instead of on a server. Paste this to your agent ````md # Add Shardlens to this Discord bot You are adding Shardlens to the discord.js bot in this repository. Everything you need is in this prompt; you don't need web access. Work through the steps in order, read before you edit, change as little as possible, and match the project's existing style (TypeScript or JavaScript, ESM or CommonJS, formatting). The samples below are TypeScript; in JavaScript, leave out the types, and in CommonJS use `require` instead of `import`. ## What Shardlens is Shardlens is self-hosted, privacy-first analytics and health monitoring for discord.js bots (MIT). - It has two parts: an **SDK** inside the bot (`@shardlens/discordjs`, what you are installing) and a **collector** with a dashboard that the bot's owner runs separately, or inside the bot in embedded mode. The SDK sends batches of events to the collector over HTTPS. - The dashboard is the owner's choice, and the SDK is the same for all three: the Shardlens dashboard (the default), a dashboard they already have (it reads every number through `@shardlens/client`), or none. If I haven't said which I want, assume the Shardlens dashboard and ask me at the end; don't build anything for the other two unless I ask. - The SDK records interactions (command name, outcome, response time), prefix commands the bot reports, servers joined and left, REST and shard health. It never records message content, and user IDs are hashed inside the bot before anything is sent. - It listens through public discord.js events only. It does not change how the bot behaves, never throws into the bot, and needs no Gateway intent beyond `Guilds`. - Requirements: discord.js 14.12 or newer, or 15; Node.js 22.12 or newer (24.11 for embedded mode). It ships ESM and CommonJS builds with types. Repository: https://github.com/Kkkermit/Shardlens · Docs: https://kkkermit.github.io/Shardlens/ ## 1. Look at the project first - `package.json` and the lockfile: which package manager is used, which discord.js version is installed, and which Node.js version the project targets. - Whether the code is TypeScript or JavaScript, and ESM (`import`) or CommonJS (`require`). TypeScript built to CommonJS (tsc, tsup, esbuild) counts as CommonJS for imports at runtime; write what the project's own source files use. - Where the discord.js `Client` is constructed (it may be a subclass, or a framework's client such as `SapphireClient` or discordx's `Client`) and where `client.login()` is called, and whether that happens at the top level of a module or inside an `async` function. - How the bot runs: one process, `ShardingManager` (find the shard file it spawns), internal sharding (`shards: 'auto'`), or discord-hybrid-sharding (`ClusterManager` and `ClusterClient`). - How commands are registered and run: the discord.js guide layout (a `commands/` folder of files with `execute`, and an `interactionCreate` file), a framework (Sapphire, discordx, CommandKit, Necord), or a loader the project wrote. Find the one place a matched command's code is called. - Whether the bot has prefix (message) commands: a `messageCreate` listener that checks a prefix or a mention, or a framework's message commands. Note whether the prefix comes from a database, whether there are aliases, and whether slash and prefix commands share the same command code. - Whether that code already catches command errors itself (a `try`/`catch` that replies "something went wrong"). - How environment variables and settings are loaded (a `.env` file, a config file, a validation schema), and whether the bot already handles `SIGINT`/`SIGTERM`. Stop and tell me, instead of continuing, if: - discord.js is older than 14.12 or Node.js is older than 22.12 (don't upgrade them yourself); - the bot has no gateway `Client` and receives interactions over HTTP (Cloudflare Workers, Deno, Bun, or `@discordjs/core` with an Interactions Endpoint URL). That bot needs `@shardlens/http` instead: https://kkkermit.github.io/Shardlens/guides/http-bots/ ## 2. Install the SDK Install `@shardlens/discordjs` with the project's own package manager. Don't add any other dependency (embedded mode, below, adds two more, and my own dashboard adds `@shardlens/client`, only if I asked for them). If the registry answers that the package doesn't exist, stop and tell me: Shardlens may not be published yet. Never install it from a tarball, a fork or a similarly named package. ## 3. Create Shardlens next to the client In the file that constructs the `Client`, after the client exists and before `client.login()`: ```ts import { createShardlens } from '@shardlens/discordjs'; const lens = createShardlens(client, { endpoint: process.env.SHARDLENS_URL, apiKey: process.env.SHARDLENS_INGEST_KEY, }); ``` In CommonJS, use `const { createShardlens } = require('@shardlens/discordjs');`. - Call it exactly once per process. - **`ShardingManager`:** put it in the shard file (the one that constructs the `Client`), never in the manager file. - **discord-hybrid-sharding:** put it in the cluster file, after `client.cluster = new ClusterClient(client)` has been set. Never in the `ClusterManager` file. - **Internal sharding** (`shards: 'auto'`) and single-process bots need nothing special. - Make `lens` reachable from wherever interactions and messages are handled, the same way the project already shares things (an export, a container). If it has no such pattern, put it on the client (`client.lens = createShardlens(…)`; in TypeScript add `lens: Shardlens` to the project's existing `declare module 'discord.js' { interface Client { … } }`, or add that declaration), so every handler reaches it as `interaction.client.lens` or `message.client.lens`. - If the project already has its version at hand (a constant, or a `package.json` it already reads), pass it as `release`. When the bot is started through an npm script, `process.env.npm_package_version` holds it too. Don't add a JSON import the project's build doesn't already allow. - If either variable is unset, the SDK logs one warning and records nothing; `lens.wrap()` and every other call still work and do nothing. The bot must still start, so don't add your own checks and don't throw. ## 4. Wrap the interaction handler `lens.wrap(handler)` takes a function whose first argument is the interaction and returns a function with the same arguments. It records how long the handler took and any error it threw, then re-throws the error unchanged, so the project's own error handling still runs. Wrap at the single place interactions are dispatched, not in every command file, and call the wrapped function exactly where and how the original was called: inside the same `try`, awaited only if the original was awaited. If the listener is already `async`, wrap the whole listener; if it isn't (it calls the handler without `await`), wrap the function it calls instead, because an `async` listener's failures go to the client's `error` event: ```ts import { Events } from 'discord.js'; client.on( Events.InteractionCreate, lens.wrap(async (interaction) => { // the existing handler body, unchanged }), ); ``` `wrap` only sees an error that leaves the function it wraps. If the project already catches command errors (a `try`/`catch` around the command call, to reply "something went wrong"), wrapping the whole listener records nothing as failed. Wrap the call inside the `try` instead, and leave the project's `catch` as it is: ```ts import { type ChatInputCommandInteraction, Events } from 'discord.js'; client.on(Events.InteractionCreate, async (interaction) => { if (!interaction.isChatInputCommand()) return; // `commands` stands for the project's own command registry const command = commands.get(interaction.commandName); if (!command) return; try { await lens.wrap((i: ChatInputCommandInteraction) => command.execute(i))(interaction); } catch (error) { // the project's existing error reply, unchanged } }); ``` Creating the wrapper on each call, as here, is cheap. With `lens` on the client it reads `interaction.client.lens.wrap(…)`, which also works when `lens` is created after the listeners are registered (in embedded mode, below). Interactions are recorded even without `wrap`; wrapping adds handler time and handler errors. If one function runs both slash and prefix commands, wrapping it is still right: `wrap` records the interactions it is given and runs anything else untouched. **If a framework runs the handlers** and emits events when a command starts and ends (Sapphire does), there is nothing to wrap. Report from those events instead, with `lens.handlerStarted(interaction)` and `lens.handlerFinished(interaction, { durationMs, error })`. For Sapphire: ```ts import { Events } from '@sapphire/framework'; client.on(Events.ChatInputCommandRun, (interaction) => lens.handlerStarted(interaction)); client.on(Events.ChatInputCommandSuccess, ({ interaction, duration }) => lens.handlerFinished(interaction, { durationMs: duration }), ); client.on(Events.ChatInputCommandError, (error, { interaction, duration }) => lens.handlerFinished(interaction, { durationMs: duration, error }), ); // Prefix commands, from the same framework: client.on(Events.MessageCommandSuccess, ({ message, command, duration }) => lens.trackMessageCommand(message, { command: command.name, durationMs: duration }), ); client.on(Events.MessageCommandError, (error, { message, command, duration }) => lens.trackMessageCommand(message, { command: command.name, durationMs: duration, error }), ); ``` Sapphire's context-menu events (`ContextMenuCommandRun`, `ContextMenuCommandSuccess`, `ContextMenuCommandError`) work the same way. **If a framework runs every command through middleware** (discordx's global guards, CommandKit middleware, Necord interceptors), wrap the framework's `next()` there, once, for both kinds of command: ```ts import { BaseInteraction, type Message } from 'discord.js'; // What the framework hands its middleware: the interaction or the message, the matched command's own name, and // `next`, which runs the command. async function shardlensMiddleware(run: BaseInteraction | Message, commandName: string, next: () => Promise) { if (run instanceof BaseInteraction) await lens.wrap((_i: BaseInteraction) => next())(run); else await lens.wrapMessageCommand(commandName, (_m: Message) => next())(run); } ``` With discordx, that is a `GuardFunction` from `discordx` added in front of the client's others (`client.guards = [guard, ...client.guards]`): its first argument is either an interaction or a `SimpleCommandMessage`, whose command name is `arg.info.name` and whose message is `arg.message`; for anything else (an event), just `await next()`. Then leave `executeInteraction` and `executeCommand` as they are. ### Prefix commands, if the bot has them Skip this if the bot has no message commands, or if a framework already reports them (above). Prefix commands (`!ban @someone`, or a mention of the bot followed by a command) are ordinary messages, so Shardlens can't see them on its own, and it never reads message content. Tell it at the single place the project runs a prefix command, after the project's own parser has found the command. Wrap the call, inside the project's `try` if there is one, like `wrap` for interactions: ```ts import type { Message } from 'discord.js'; async function runPrefixCommand(message: Message, name: string, args: string[]) { // `prefixCommands` stands for the project's own registry of message commands const command = prefixCommands.get(name); if (!command) return; try { // The command's own name, after aliases: never the text that was typed. await lens.wrapMessageCommand(command.name, (m: Message) => command.execute(m, args))(message); } catch { // the project's existing error reply, unchanged } } ``` Where a wrapper doesn't fit the code (the run ends in a callback, or only the project's `catch` knows it failed), report the run once it is over: ```ts import type { Message } from 'discord.js'; async function runPrefixCommand(message: Message, name: string, args: string[]) { const command = prefixCommands.get(name); if (!command) return; const started = performance.now(); let failed = false; try { await command.execute(message, args); } catch { failed = true; // the project's existing error reply, unchanged } lens.trackMessageCommand(message, { command: command.name, durationMs: performance.now() - started, failed }); } ``` If each command catches its own errors, so that nothing leaves it, either form records every run and its duration, but as a success. Don't edit every command for it: say so in your summary. - If the command has a subcommand, pass `{ command, sub }` to `wrapMessageCommand` or add `sub` to the `trackMessageCommand` object. - Pass the command's own name after the project's parser has matched it (aliases resolved, prefix removed). A per-server prefix from a database, aliases and mentions make no difference. - Only record what the parser matched: a message that isn't a known command must not be recorded, and checks that refuse to run a command (server only, missing permission) can stay outside the wrapped call. - Never pass `message.content`, the typed name, argument values or anything else the user wrote. - Record prefix commands only with `trackMessageCommand` or `wrapMessageCommand`, never as a custom event with `track()`: only those show up next to slash commands. - Don't add the Message Content intent for Shardlens. If the bot has prefix commands it already has it. ## 5. Flush on shutdown The SDK never installs signal handlers. On the bot's existing shutdown path, `await lens.shutdown()` before the client is destroyed or the process exits. If the bot has no shutdown handling, add it in the file that creates `lens`: ```ts for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await lens.shutdown(); await client.destroy(); process.exit(0); }); } ``` `shutdown()` gives up after 2 seconds and never throws. Calling it a second time waits for the same flush. **With `ShardingManager` or discord-hybrid-sharding**, that handler goes in the shard or cluster file. A signal sent to the manager alone (`docker stop`, systemd, a host's restart) never reaches those processes: they keep running, and are killed without flushing when the container or service stops. So also add this to the manager file, before `spawn()`, or to its existing signal handler. For `ShardingManager`: ```ts import { once } from 'node:events'; import type { ShardingManager } from 'discord.js'; declare const manager: ShardingManager; // the project's own manager for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await Promise.all( manager.shards.map((shard) => { const child = shard.process; if (!child || child.exitCode !== null) return undefined; shard.kill(); // SIGTERM to the shard, which then flushes and exits return once(child, 'exit'); }), ); process.exit(0); }); } ``` For discord-hybrid-sharding's `ClusterManager` (in `mode: 'process'`, the default): ```ts import { once } from 'node:events'; import { Child, type ClusterManager } from 'discord-hybrid-sharding'; declare const manager: ClusterManager; // the project's own manager for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await Promise.all( [...manager.clusters.values()].map((cluster) => { const child = cluster.thread instanceof Child ? cluster.thread.process : null; if (!child || child.exitCode !== null) return undefined; cluster.kill({ force: true, reason: signal }); return once(child, 'exit'); }), ); process.exit(0); }); } ``` ## 6. Document the two settings Skip this step in embedded mode, which uses neither setting. Add `SHARDLENS_URL=` and `SHARDLENS_INGEST_KEY=` (empty) to `.env.example` or wherever the project documents its environment. If the project validates its environment (zod, envalid, a config file), declare both as **optional strings and nothing more**: no format checks, no "both or neither" rule, no failure. The SDK checks them itself, logs one warning and records nothing when they are wrong. Add one line about Shardlens to the README's setup section if there is one. - `SHARDLENS_URL` is the collector's address, for example `https://stats.example.com`. It must be HTTPS (plain HTTP is accepted for `localhost` only). - `SHARDLENS_INGEST_KEY` looks like `slk_ingest_…`. It can only send events; it cannot read anything. ## Rules - Never write a real key, token or URL with credentials into a tracked file, and never log one. - Don't add or change Gateway intents. Shardlens must never be the reason a privileged intent is enabled. - Leave privacy mode on: don't set `mode: 'audit'` or `captureOptionValues` unless I ask. - Don't wrap SDK calls (`createShardlens`, `lens.*`) in `try`/`catch`: the SDK never throws into the bot. - Don't change command behaviour, error handling or anything unrelated to these steps. - The bot must start and behave exactly as before when Shardlens isn't configured, is misconfigured or the collector is down. Never add a check that stops it from starting, and never exit or throw because of Shardlens. - Do these steps and nothing more. No status commands, owner panels, API routes, dashboards, extra settings (such as a dry-run variable), privacy-notice rewrites or tests of your own invention unless I ask. Suggest them in your summary instead. - Use the SDK's own methods for what they cover. Don't invent event names or send your own versions of what the SDK records. - Never print, log, echo or paste a secret or any part of one (keys, tokens, session secrets, settings keys), not even while testing. Say where it is stored instead. ## Only if I ask for them **Custom events.** Names are lower snake case; properties are small strings, numbers, booleans or nulls. Never put a user ID, a username or message text in the properties. Pass the user as context, where it is hashed: ```ts lens.track('ticket_opened', { category: 'billing' }, { userId: interaction.user.id, guildId: interaction.guildId }); ``` **A `/privacy` command** that lets users see what is collected, opt out and ask for erasure: ```ts import { createPrivacyCommand } from '@shardlens/discordjs'; const privacy = createPrivacyCommand(lens, { policyUrl: 'https://example.com/privacy' }); // Register `privacy.data` with the project's other commands, then, at the top of the interaction handler: if (interaction.isChatInputCommand() && (await privacy.handle(interaction))) { // handled } ``` Opt-outs are held in memory, so the command's "no longer recorded" reply stops being true at the next restart unless they are saved. If the project has a database, save them there: pass the saved IDs as `optedOut` and save changes in `onOptOutChange` (both options of `createShardlens`; the callback may be `async`, and a failed save is counted, never thrown). If it has none, tell me instead of choosing a store yourself. Also tell me to register the command with Discord if the project registers commands in a separate deploy script. **My own dashboard.** To show Shardlens numbers in a dashboard or admin panel I already have, install `@shardlens/client` on that panel's server side and ask the collector there. It has no dependencies and uses `fetch`. Never call it from code that runs in a browser: the key would be readable by whoever opens the page. If the panel is a project of its own, without the bot in it, do only this section there: steps 1 to 6 are for the bot. ```ts import { createShardlensClient, lastDays } from '@shardlens/client'; const shardlens = createShardlensClient({ endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_READ_KEY!, }); const { rows } = await shardlens.commands({ range: lastDays(7) }); // every command: runs, failures, p95, servers const ticket = await shardlens.command('ticket', { range: lastDays(30) }); // one command in depth const failing = await shardlens.top({ metric: 'interactions', groupBy: 'command', filters: [ { field: 'guild', value: '112233445566778899' }, { field: 'outcome', op: 'in', value: ['error', 'timeout', 'no_response'] }, ], range: lastDays(30), }); // the commands that fail in one server ``` - There is one method per kind of answer (`overview`, `commands`, `command`, `series`, `top`, `heatmap`, `servers`, `server`, `growth`, `audience`, `reliability`, `gauge`, `bursts`, `premium`, `installs`, `events`, `eventProps`, `funnel`, `retention`), `meta()`, and `live()` for the live numbers. Answers are typed; a failed request throws `ShardlensClientError`. Cache answers for a minute: the collector rolls numbers up once a minute. - It needs two settings where the panel's server runs, `SHARDLENS_URL` (the collector's address, with no path) and `SHARDLENS_READ_KEY` (a read key, `slk_read_…`, not the bot's ingest key). Document them the way step 6 documents the bot's two, and don't make the panel fail to start without them: making the client never throws, and without its settings each call rejects with `invalid_options`, so show "not set up" on those pages instead. - Follow the panel's existing patterns for routes, data loading and sign-in, and add pages only for what I asked to see. - Who ran what is separate. Only if I asked for audit mode: `shardlens.activity.log({ guild, command, user, outcome: 'failed', before })` (newest first, 50 rows a page; pass a page's `nextBefore` as `before` for the next) and `shardlens.activity.topUsers('7d')` read it, with `SHARDLENS_ACTIVITY_KEY` (an activity key, `slk_activity_…`) as the client's `apiKey`, on pages only my own staff can open. Never put a user ID in a URL a browser's address bar shows, and add no page that profiles one user beyond that exact-ID lookup. - Tell me to set the collector up with `npx shardlens init … --dashboard own` (add `--identify-users` for who ran what): it turns the Shardlens dashboard off and writes `dashboard.env` with these settings. Guide: https://kkkermit.github.io/Shardlens/guides/your-own-dashboard/ **Embedded mode**, for a small bot on one host with no separate collector: the collector and its dashboard run inside the bot process, with their data in one folder. - It runs in one process. If the bot uses `ShardingManager` or discord-hybrid-sharding, stop and tell me: those need a standalone collector. Internal sharding is fine. - It needs Node.js 24.11 or newer. If the project targets an older Node.js, stop and tell me. - Install `@shardlens/collector` and `@electric-sql/pglite` as well as the SDK. In CommonJS, `require('@shardlens/collector/embedded')` works on Node.js 24. - It needs the application ID (from the Developer Portal). Use the setting the project already has for it (often `CLIENT_ID`, `APPLICATION_ID` or a `clientId` in its config); only if it has none, add `DISCORD_APP_ID` next to the bot's other settings. - The dashboard listens on port 8080 of this machine. Pick another port if the project already uses 8080. - If I said I want my own dashboard or none, pass `dashboard: false`: the collector then serves its API only, and `collector.readKey` is the key `@shardlens/client` needs (with `endpoint: collector.url`). - Add the data folder (`shardlens-data` below) to `.gitignore`. Skip step 6: the collector's own address and key replace the two settings. The collector has to start before `createShardlens`, because the SDK needs its address and key: ```ts import { startEmbeddedCollector } from '@shardlens/collector/embedded'; import { createShardlens } from '@shardlens/discordjs'; // Unlike the SDK, the embedded collector can fail to start: a port in use, a folder it can't write to, a missing // application ID. Catch that, so the bot starts without analytics instead of not starting. const collector = await startEmbeddedCollector({ dataDir: './shardlens-data', appId: process.env.DISCORD_APP_ID ?? '', port: 8080, }).catch((error: unknown) => { console.error('Shardlens: the embedded collector did not start.', error); return undefined; }); const lens = createShardlens(client, { endpoint: collector?.url, apiKey: collector?.ingestKey }); for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await lens.shutdown(); // first, while the collector can still take the last events await client.destroy(); await collector?.close(); process.exit(0); }); } ``` This uses top-level `await`, which needs an ES module. In CommonJS, or where the bot starts inside an `async` function, put these lines in that function (create one around `client.login()` if there is none), before `client.login()`. `lens` then doesn't exist yet when the module registers its listeners, so put it on the client (`client.lens = createShardlens(…)`) and use `client.lens` inside the listeners, creating wrappers on each call as in step 4. The dashboard is then at `http://127.0.0.1:8080`, and the key to sign in with is `readKey` in `shardlens-data/secrets.json`: tell me where it is, never print it. **Your own database.** To also keep every event in the database the bot already uses (MongoDB, MySQL, MariaDB, PostgreSQL or SQLite), the collector copies them there; the bot's code doesn't change. With a standalone collector, tell me to set `SHARDLENS_SINK_URL` on the collector. With embedded mode, pass the connection URL the project already reads (never a hard-coded one) as `sink`: ```ts import { startEmbeddedCollector } from '@shardlens/collector/embedded'; const databaseUrl = process.env.MONGODB_URI; // the setting the bot already uses for its own database const collector = await startEmbeddedCollector({ dataDir: './shardlens-data', appId: process.env.DISCORD_APP_ID ?? '', ...(databaseUrl ? { sink: { to: databaseUrl } } : {}), }).catch(() => undefined); ``` **Other options** of `createShardlens`: `environment` (default `'production'`), `dryRun` (print events instead of sending them), `disable` (turn off groups: `'interactions'`, `'guilds'`, `'rest'`, `'gateway'`, `'process'`, `'premium'`, `'app'`), `optedOut` and `onOptOutChange` (persist opt-outs), `spool: { dir }` (keep events on disk through long collector outages), `exporters` (Prometheus or OpenTelemetry), `sampleRate` (very large bots), `refreshGuildCounts` (keep member counts current). Every option is documented in the package's type definitions (`node_modules/@shardlens/discordjs/dist/index.d.ts`). ## Check your work - Run the project's own type-check, lint, build and test scripts, and fix anything you broke. - If `SHARDLENS_URL` and `SHARDLENS_INGEST_KEY` are set in my environment or the bot's `.env`, run `npx shardlens doctor` from the bot's folder and show me its output. It checks Node.js, discord.js, the collector and the key. Never print the key. - Don't start the bot yourself unless I ask. ## Tell me when you're done - Which files you changed, and what each change does. - What I still need to do: 1. With a standalone collector: run one with `npx shardlens init --domain --app-id `, then `docker compose up -d` in the folder it creates. Ask me which dashboard I want if I haven't said: the Shardlens dashboard (nothing to add), my own (`--dashboard own`) or none (`--dashboard none`); https://kkkermit.github.io/Shardlens/getting-started/choose-your-setup/ compares them. It prints nothing secret; the bot's two settings are in the generated `bot.env`. Guide: https://kkkermit.github.io/Shardlens/getting-started/quick-start/ Then set `SHARDLENS_URL` and `SHARDLENS_INGEST_KEY` where the bot runs. 2. In embedded mode instead: set the application ID if you added a setting for it, start the bot, and open the dashboard with the read key (say where it is). 3. To see what would be sent before any of that, pass `dryRun: true` once and run a command in the bot. - Anything you skipped or weren't sure about. ## If you need more The whole documentation is available as plain text for agents: an index at https://kkkermit.github.io/Shardlens/llms.txt and everything in one file at https://kkkermit.github.io/Shardlens/llms-full.txt. The collector's HTTP API, as an OpenAPI document: https://kkkermit.github.io/Shardlens/openapi.json. What is collected, field by field: https://kkkermit.github.io/Shardlens/concepts/data-collected/ ```` ## Point your agent at a URL instead [Section titled “Point your agent at a URL instead”](#point-your-agent-at-a-url-instead) The same prompt is served as plain Markdown, so you can skip the copying: ```text Add Shardlens to this bot by following https://kkkermit.github.io/Shardlens/install.md ``` The prompt is self-contained: it explains what Shardlens is, how to find your client and handler, what to do for each sharding mode, which settings to document, what the agent must not change, and how to check its work. Its TypeScript samples are type-checked against the real packages on every build of these docs. Review what it did Read the diff before you commit, as with any generated change. The prompt tells the agent not to touch intents, not to turn on audit mode, never to write or print a key, never to let a Shardlens setting stop your bot from starting, and not to add anything you didn’t ask for. Check that it listened. ## What the agent doesn’t do [Section titled “What the agent doesn’t do”](#what-the-agent-doesnt-do) The prompt only changes your bot. You still need somewhere for the events to go: 1. Start a collector: follow step 1 of the [quick start](../quick-start/). In [embedded mode](../../self-hosting/embedded/) the collector runs inside your bot, so there is nothing to start. 2. Set `SHARDLENS_URL` and `SHARDLENS_INGEST_KEY` wherever your bot runs. 3. Run `npx shardlens doctor` from your bot’s folder to check the connection. ## These docs, for agents [Section titled “These docs, for agents”](#these-docs-for-agents) The whole documentation is also published as plain text, following the [llms.txt](https://llmstxt.org/) convention: | File | What it holds | | ------------------------------------------------------------------------ | --------------------------------------------------------- | | [`/llms.txt`](https://kkkermit.github.io/Shardlens/llms.txt) | A short description of Shardlens and an index of the docs | | [`/llms-small.txt`](https://kkkermit.github.io/Shardlens/llms-small.txt) | Guides and concepts, trimmed for small context windows | | [`/llms-full.txt`](https://kkkermit.github.io/Shardlens/llms-full.txt) | Every page in one file, including the SDK reference | | [`/openapi.json`](https://kkkermit.github.io/Shardlens/openapi.json) | The collector’s HTTP API as an OpenAPI 3.1 document | | [`/install.md`](https://kkkermit.github.io/Shardlens/install.md) | The install prompt on this page | Nothing on this site blocks crawlers, and a [sitemap](https://kkkermit.github.io/Shardlens/sitemap-index.xml) lists every page. ## Doing it by hand [Section titled “Doing it by hand”](#doing-it-by-hand) Every step in the prompt is covered in these docs: [installation](../installation/), [configuration](../configuration/), [wrapping handlers](../../guides/wrapping-handlers/) and [sharding](../../guides/sharding/). # Installation > Requirements and installing the Shardlens SDK. ## Requirements [Section titled “Requirements”](#requirements) | What | Version | | ---------- | ----------------------------------------------------------------- | | Node.js | 22.12 or later (24 LTS recommended; 24.11 for embedded mode) | | discord.js | 14.12 or later, and 15 | | Intents | `Guilds` only. No privileged intents. | | Collector | Any server with Docker, or Railway or Render. PostgreSQL 16 or 17 | The SDK ships ESM and CommonJS builds with type definitions, so it works with `import` and `require`, TypeScript and plain JavaScript. ## Install [Section titled “Install”](#install) * pnpm ```sh pnpm add @shardlens/discordjs ``` * npm ```sh npm install @shardlens/discordjs ``` * yarn ```sh yarn add @shardlens/discordjs ``` * bun ```sh bun add @shardlens/discordjs ``` `discord.js` is a peer dependency: the SDK uses the copy your bot already has. Releases before 14.12 use an older REST client whose responses Shardlens can’t read, so it needs 14.12 or later. ## Packages [Section titled “Packages”](#packages) | Package | What it is | | ---------------------- | ---------------------------------------------------------------------------------------------- | | `@shardlens/discordjs` | The discord.js adapter. This is the one you install. | | `@shardlens/core` | Zero-dependency core used by the adapter: queue, salts, hashing, batching, retries, redaction. | | `@shardlens/schema` | The wire format (zod), JSON Schema, and the metric and data-collected registers. | | `shardlens` | The [CLI](../../reference/cli/): `init`, `keys`, `privacy`, `doctor`. | ## Check your setup [Section titled “Check your setup”](#check-your-setup) ```sh npx shardlens doctor --url https://stats.example.com --key slk_ingest_… ``` `doctor` checks your Node and discord.js versions, that the collector is reachable over HTTPS and that it accepts your key. Run it from your bot’s folder so it finds the right discord.js. Note Shardlens uses public discord.js APIs only (no monkey-patching), so discord.js updates don’t break it. # Quick start > Self-host Shardlens and send your bot's first events in under 10 minutes. You need a server with Docker and a domain name pointing at it (for HTTPS), and a bot on discord.js 14.12 or later, or 15. Already have a dashboard, or want none? This page sets up the Shardlens dashboard. To show the numbers in a dashboard of your own, or to run without one, see [Choose your setup](../choose-your-setup/): the steps for your bot are the same. 1. **Start the collector** `shardlens init` writes `docker-compose.yml`, a `Caddyfile`, a `.env` with generated secrets and keys, and a `bot.env` holding the two settings your bot needs. ```sh npx shardlens init --domain stats.example.com --app-id 123456789012345678 cd shardlens && docker compose up -d ``` Caddy gets a certificate for your domain, the collector creates its tables, and the dashboard is served at `https://stats.example.com`. The bot’s two settings are in `bot.env`. 2. **Install the SDK in your bot** * pnpm `pnpm add @shardlens/discordjs` * npm `npm install @shardlens/discordjs` * yarn `yarn add @shardlens/discordjs` * bun `bun add @shardlens/discordjs` 3. **Add three lines to your bot** bot.ts ```ts import { createShardlens } from '@shardlens/discordjs'; import { Client, GatewayIntentBits } from 'discord.js'; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); createShardlens(client, { endpoint: process.env.SHARDLENS_URL!, // https://stats.example.com apiKey: process.env.SHARDLENS_INGEST_KEY!, // slk_ingest_… }); await client.login(process.env.DISCORD_TOKEN); ``` Copy the two lines from `bot.env` (`SHARDLENS_URL` and `SHARDLENS_INGEST_KEY`) to wherever your bot reads its settings, then delete `bot.env`. 4. **Open the dashboard** Go to your domain and sign in with your read key (`SHARDLENS_READ_KEY` in `.env`), or with Discord once you have [set up Discord sign-in](../../self-hosting/docker-compose/#discord-sign-in). Run a command in your bot: the live tiles on the Overview count it within seconds, and the chart and checklist follow within a minute or two, without reloading. Tip Only the `Guilds` intent is needed. Shardlens never reads message content and user IDs never leave your bot. ## Next steps [Section titled “Next steps”](#next-steps) * [Configuration](../configuration/): every SDK option. * [Wrapping handlers](../../guides/wrapping-handlers/): record handler time and errors. * [The `/privacy` command](../../guides/privacy-command/): let users opt out or ask for erasure. * [What is collected](../../concepts/data-collected/): every field, generated from the wire format. # Alerts > Get a Discord message when your bot misses deadlines, fails, or loses shards. Alerts post to a Discord channel through a webhook when a metric crosses a threshold for a period of time, for example “missed deadlines above 1% for 10 minutes”. ## Create an alert [Section titled “Create an alert”](#create-an-alert) 1. In Discord, open the channel’s settings → **Integrations → Webhooks → New Webhook**, and copy its URL. 2. In the dashboard, open **Alerts** (Discord sign-in required) and fill in **New alert**: a name, the metric, a comparison, a threshold and a window between 1 minute and 24 hours. 3. Press **Create**, then use **Test** on the rule’s row to send a test message. ## Metrics you can alert on [Section titled “Metrics you can alert on”](#metrics-you-can-alert-on) | Metric | Meaning | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `missed_deadline_rate` | Share of interactions with no response within 3 seconds, in percent (prefix commands have no deadline and don’t count) | | `error_rate` | Share of interactions and prefix commands that failed, in percent | | `p95_ms` | 95th-percentile time to first response, in milliseconds | | `invalid_requests_pct` | Share of the invalid-request limit (10,000 per 10 minutes) used | | `stale_shards` | Shards that haven’t reported within the window | | `interactions_per_min` | Interactions (commands, buttons, menus, modals, autocomplete) and prefix commands per minute; alert on a drop with `<` | | `identify_remaining` | Gateway sessions left in Discord’s daily budget | ## How alerts behave [Section titled “How alerts behave”](#how-alerts-behave) * Rules are checked every minute, over the window you chose. The invalid-request budget always looks at the last 10 minutes, because that is the window Discord’s limit uses. * An alert that fired won’t fire again for 30 minutes, so a long incident doesn’t flood the channel. Every firing is kept in the alert history, with the reason when Discord didn’t take the message (see [Troubleshooting](../../operations/troubleshooting/#alerts-or-reports-dont-arrive)). * With no data in the window (no interactions yet, say), the rate and latency metrics have no value and don’t fire. * Messages use Discord’s Components V2 layout with a link back to the dashboard, falling back to a plain message if needed. Note Only Discord webhook URLs (`https://discord.com/api/webhooks/…`) are accepted, and they are stored encrypted. The dashboard only ever shows them masked. # Hashed or identified users > Choose whether user IDs are hashed or recorded. Audit mode records who ran a command; here is when that is appropriate, how to turn it on, and the guardrails around it. You choose whether Shardlens hashes user IDs or records them. | | Hashed (privacy mode, the default) | Identified (audit mode) | | -------------------- | ----------------------------------------------------- | -------------------------------------------------- | | What leaves your bot | A salted hash that can’t be turned back into an ID | The user ID, username and avatar, and nothing else | | What you can see | How many people, never which people | Who ran each interaction, in the **Activity** log | | How long it is kept | Hashes become unlinkable when their salt is destroyed | 30 days by default, 90 at most, encrypted | Identified mode exists so moderators and support staff can answer “who used `/ban` in this server yesterday?” or investigate abuse. Everything else in Shardlens (command usage, servers, growth, response times) works the same in both modes, and is always counts. ## What “identified” collects [Section titled “What “identified” collects”](#what-identified-collects) Exactly three things about the person who ran an interaction: their **user ID**, their **username** and their **avatar** (so the Activity log can show a profile picture). No email address, display name, roles, connections or message content, in any mode. Set `auditIncludeProfile: false` in the SDK to record the ID alone. ## When it is appropriate [Section titled “When it is appropriate”](#when-it-is-appropriate) Use audit mode when you have a support or abuse-handling need that counts can’t meet, and you can explain it to your users. Don’t turn it on for curiosity or marketing. Developer Policy, rule 15 Collect only what is necessary for the functionality you describe; use aggregated or de-identified data to improve your app. **Shardlens:** Privacy mode is the default. Audit mode is framed as support and abuse-handling functionality, with guardrails. Turning it on changes what you collect, so update your privacy policy first. `npx shardlens privacy --audit` prints a paragraph that matches. ## Turn it on [Section titled “Turn it on”](#turn-it-on) Audit mode has to be switched on in **both** places. One side alone does nothing. 1. **Give the collector an audit key** Setting up from scratch? `npx shardlens init --identify-users …` creates it for you. Otherwise: ```sh openssl rand -base64 32 ``` Put the result in `.env` as `SHARDLENS_AUDIT_KEY` and restart the collector. Keep a copy somewhere safe: audit data can’t be read without it. 2. **Choose “Identified” on the collector** In the dashboard, **Settings → User identity → Mode: Identified**. Only a Discord sign-in (owner or team) can change it. Running the collector [without the Shardlens dashboard](../../getting-started/choose-your-setup/)? Set `SHARDLENS_MODE=audit` in its `.env` instead (`mode: 'audit'` for an embedded collector) and restart it. `npx shardlens init … --dashboard own --identify-users` writes both lines for you. 3. **Switch the SDK to audit mode** bot.ts ```ts import { createShardlens } from '@shardlens/discordjs'; import { Client, GatewayIntentBits } from 'discord.js'; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); createShardlens(client, { endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_INGEST_KEY!, mode: 'audit', // only takes effect when the collector is in audit mode too auditIncludeProfile: true, // the default: username and avatar with each user ID. false records IDs only }); ``` ## Finding who ran into a failure [Section titled “Finding who ran into a failure”](#finding-who-ran-into-a-failure) When someone reports that a command “did nothing”, open the server’s page or the command’s page and follow **View failed runs**: the Activity log opens already narrowed to the runs that errored, missed the 3-second deadline or got no response. The same filters are in the log itself (command, server ID, outcome, exact user ID), and its address can be linked to from your own tools: `/activity?guild=&outcome=failed`. A user ID is never part of the address. Shardlens records and shows; it doesn’t act on users. Blocking someone is your bot’s job: copy the user ID from the log into your bot’s own block command or admin panel, or read the log from that panel as below. ## Read it from your own dashboard [Section titled “Read it from your own dashboard”](#read-it-from-your-own-dashboard) The activity log isn’t tied to the Shardlens dashboard. An **activity key** (`slk_activity_…`) reads it from the server side of a dashboard of your own, through [`@shardlens/client`](../your-own-dashboard/#who-ran-what): lib/shardlens-activity.ts ```ts // Runs on your dashboard's server, behind your own sign-in: these answers name people. import { createShardlensClient } from '@shardlens/client'; const shardlens = createShardlensClient({ endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_ACTIVITY_KEY!, // slk_activity_…: who ran what, and everything a read key reads }); // The latest failed runs in one server, with who ran each. Pass `nextBefore` back as `before` for the next page. export function failedRunsIn(guildId: string, before?: string | null) { return shardlens.activity.log({ guild: guildId, outcome: 'failed', limit: 50, before }); } // Everything one user ran, newest first: for a support ticket or an abuse report. Exact IDs only. export function runsBy(userId: string) { return shardlens.activity.log({ user: userId }); } // The most active users of the last 7 days, as counts. export function busiestUsers() { return shardlens.activity.topUsers('7d'); } ``` Create one in **Settings → API keys → New activity key**, with `npx shardlens init … --dashboard own --identify-users`, or with `npx shardlens keys --scope activity` and `SHARDLENS_ACTIVITY_KEY` in the collector’s `.env`. An activity key reads the log and the top users, and everything a read key reads. It can’t export the log, change settings or sign in to the Shardlens dashboard, and it is answered with `404 audit_mode_off` while users are hashed. Treat it like a password to personal data: keep it on a server, behind a sign-in of your own for your own staff, and revoke it in **Settings → API keys** when it is no longer needed. Without the dashboard, put a new key in `SHARDLENS_ACTIVITY_KEY` and restart the collector: the old one stops working. To stop reading the log altogether, switch audit mode off (`SHARDLENS_MODE=privacy`). ## Guardrails [Section titled “Guardrails”](#guardrails) * **Encrypted at rest** with AES-256-GCM, using a key that lives outside the database. * **Kept for 30 days** by default. You can choose up to 90; longer is rejected. * **Every access is logged**: viewing the activity log, looking up a user, viewing top users and exporting, by a person or by an activity key (under the key’s label; the same read repeated by a key within a minute, as a page that refreshes does, is one entry). The log is visible under **Settings → Privacy**; with the dashboard off it is still written, and turning the dashboard on shows it. * **Exact lookups only**: you can search for a known user ID, but there is no browsing of user profiles and the query API can’t group by user. * **Exports need confirmation**, and spreadsheet formulas in the CSV are neutralised. * **Three fields, no more**: user ID, username and avatar. `auditIncludeProfile: false` keeps the ID only. Developer Policy, rule 16 No profiling of users or their relationships. **Shardlens:** No per-user profile pages, and the query API cannot group by user. A complete bot is in [`examples/audit-mode`](https://github.com/Kkkermit/Shardlens/tree/main/examples/audit-mode). ## Turning it off [Section titled “Turning it off”](#turning-it-off) Switch the collector back to **Hashed** in Settings. New interactions are stored without identities straight away; existing audit rows expire on their normal schedule, or you can erase individual users. # Badges > Opt-in SVG badges for your README or bot-list page. Shardlens can serve public SVG badges with a headline number. Every badge is **off** until you switch it on. | Badge | URL | Shows | | ---------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------- | | Servers | `/v1/badge/servers.svg` | Servers the bot is in | | Monthly users | `/v1/badge/users-monthly.svg` | Unique users so far in the current salt period: this month, or this week or day if Settings rotates salts more often | | Commands per day | `/v1/badge/commands-daily.svg` | Commands run in the last 24 hours (slash, context menu and prefix commands) | ## Turn one on [Section titled “Turn one on”](#turn-one-on) In the dashboard, **Settings → Public badges**, tick the badges you want and save. Then use the URL in Markdown: ```md ![Servers](https://stats.example.com/v1/badge/servers.svg) ``` A badge that is switched off answers `404`, so nothing is public by accident. ## Caching [Section titled “Caching”](#caching) Badges are cached for 10 minutes on the collector and tell browsers and image proxies to cache for 10 minutes too. The endpoint is rate limited. Note Numbers on badges are shortened (for example `1.2K`). Turning on a badge makes that number public; nothing else about your bot is exposed. # Command handlers and frameworks > Where Shardlens goes in bots built from the discord.js guide, in JavaScript or TypeScript, and with Sapphire or other frameworks. Every bot is laid out differently, but Shardlens only ever needs four things, wherever they live in yours: 1. **One `createShardlens(client, …)`** per process, after the client is created and before `client.login()`. That alone records every slash command, context menu, button, select menu, modal and autocomplete. 2. **Handler time and failures** (optional): run your command code through [`lens.wrap()`](../wrapping-handlers/), or tell Shardlens when your framework starts and finishes a handler. 3. **Prefix commands**, if you have them: one [`trackMessageCommand`](../prefix-commands/) call where a message is matched to a command. 4. **`await lens.shutdown()`** on your existing shutdown path. The rest of this page shows where those go in common layouts. ## Reaching `lens` from other files [Section titled “Reaching lens from other files”](#reaching-lens-from-other-files) Handlers usually live in their own files. The simplest way to reach `lens` from all of them is to keep it on the client, which every interaction and message already carries: * TypeScript ```ts import { createShardlens, type Shardlens } from '@shardlens/discordjs'; declare module 'discord.js' { interface Client { lens: Shardlens; } } client.lens = createShardlens(client, { endpoint: process.env.SHARDLENS_URL, apiKey: process.env.SHARDLENS_INGEST_KEY }); // anywhere else: interaction.client.lens, message.client.lens ``` * JavaScript (CommonJS) ```js const { createShardlens } = require('@shardlens/discordjs'); client.lens = createShardlens(client, { endpoint: process.env.SHARDLENS_URL, apiKey: process.env.SHARDLENS_INGEST_KEY, }); // anywhere else: interaction.client.lens, message.client.lens ``` * JavaScript (ESM) ```js import { createShardlens } from '@shardlens/discordjs'; client.lens = createShardlens(client, { endpoint: process.env.SHARDLENS_URL, apiKey: process.env.SHARDLENS_INGEST_KEY, }); ``` If your project already shares things another way (an exported module, a container, a `bot` object), keep `lens` with them instead. `createShardlens` must still run once per process. ## The discord.js guide layout [Section titled “The discord.js guide layout”](#the-discordjs-guide-layout) A `commands/` folder with an `execute` function per command, an `events/` folder, and a loader in `index.js`. Wrap the `execute` call inside the existing `try`, so failures reach Shardlens and your error reply still runs: index.ts and events/interactionCreate.ts ```ts // The layout from the discord.js guide: one file per command with `execute`, one `interactionCreate` file, and the // client created in index.ts. `lens` travels on the client, so every file reaches it as `interaction.client.lens`. import { createShardlens, type Shardlens } from '@shardlens/discordjs'; import { type ChatInputCommandInteraction, Client, Collection, Events, GatewayIntentBits, MessageFlags, } from 'discord.js'; declare module 'discord.js' { interface Client { lens: Shardlens; commands: Collection }>; } } // index.ts const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.commands = new Collection(); client.lens = createShardlens(client, { endpoint: process.env.SHARDLENS_URL, apiKey: process.env.SHARDLENS_INGEST_KEY, }); // events/interactionCreate.ts const interactionCreate = { name: Events.InteractionCreate, async execute(interaction: ChatInputCommandInteraction) { const command = interaction.client.commands.get(interaction.commandName); if (!command) return; try { // Wrapped inside the try, so the error reaches Shardlens on its way to your catch. await interaction.client.lens.wrap((i: ChatInputCommandInteraction) => command.execute(i))(interaction); } catch { const reply = { content: 'There was an error while running this command.', flags: MessageFlags.Ephemeral, } as const; if (interaction.replied || interaction.deferred) await interaction.followUp(reply); else await interaction.reply(reply); } }, }; export { interactionCreate }; ``` Buttons, select menus and modals handled in the same file need nothing more: they are recorded on their own. Wrap their handlers the same way if you want their handler time. ## Sapphire [Section titled “Sapphire”](#sapphire) Sapphire runs commands itself and emits an event at each step, so there is nothing to wrap. Listen to those events: index.ts ```ts import { Events, SapphireClient } from '@sapphire/framework'; import { createShardlens } from '@shardlens/discordjs'; import { GatewayIntentBits } from 'discord.js'; const client = new SapphireClient({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent], loadMessageCommandListeners: true, }); const lens = createShardlens(client, { endpoint: process.env.SHARDLENS_URL, apiKey: process.env.SHARDLENS_INGEST_KEY, }); // Sapphire runs your commands and announces each step; Shardlens listens. Interactions are recorded on their own: // these add handler time and failures, as lens.wrap() would. client.on(Events.ChatInputCommandRun, (interaction) => lens.handlerStarted(interaction)); client.on(Events.ChatInputCommandSuccess, ({ interaction, duration }) => lens.handlerFinished(interaction, { durationMs: duration }), ); client.on(Events.ChatInputCommandError, (error, { interaction, duration }) => lens.handlerFinished(interaction, { durationMs: duration, error }), ); client.on(Events.ContextMenuCommandRun, (interaction) => lens.handlerStarted(interaction)); client.on(Events.ContextMenuCommandSuccess, ({ interaction, duration }) => lens.handlerFinished(interaction, { durationMs: duration }), ); client.on(Events.ContextMenuCommandError, (error, { interaction, duration }) => lens.handlerFinished(interaction, { durationMs: duration, error }), ); // Prefix commands: the command's name, never what was typed. client.on(Events.MessageCommandSuccess, ({ message, command, duration }) => lens.trackMessageCommand(message, { command: command.name, durationMs: duration }), ); client.on(Events.MessageCommandError, (error, { message, command, duration }) => lens.trackMessageCommand(message, { command: command.name, durationMs: duration, error }), ); await client.login(process.env.DISCORD_TOKEN); ``` `handlerStarted(interaction)` and `handlerFinished(interaction, { durationMs, error })` record exactly what `wrap()` would. Use them with any framework that tells you when a handler starts and ends. ## discordx [Section titled “discordx”](#discordx) discordx runs every slash command, context menu, component and simple (prefix) command through its guards, and a command’s error comes back out of `next()`. One global guard, in front of any you have, covers both kinds of command: ```ts import { createShardlens } from '@shardlens/discordjs'; import { BaseInteraction } from 'discord.js'; import { type GuardFunction, SimpleCommandMessage } from 'discordx'; const lens = createShardlens(bot, { endpoint: process.env.SHARDLENS_URL, apiKey: process.env.SHARDLENS_INGEST_KEY }); const shardlensGuard: GuardFunction = async (arg, _client, next) => { if (arg instanceof SimpleCommandMessage) { // The command's own name: aliases and the per-server prefix are already resolved. await lens.wrapMessageCommand(arg.info.name, () => next())(arg.message); } else if (arg instanceof BaseInteraction) { await lens.wrap((_interaction: BaseInteraction) => next())(arg); } else { await next(); // events } }; bot.guards = [shardlensGuard, ...bot.guards]; ``` Leave `bot.executeInteraction()` and `bot.executeCommand()` as they are. ## Other frameworks and hand-made handlers [Section titled “Other frameworks and hand-made handlers”](#other-frameworks-and-hand-made-handlers) The same rule works for any layout (CommandKit, Necord, a loader you wrote): * Find the one place a matched command’s code is called. Wrap that call with `lens.wrap()` (interactions) or `lens.wrapMessageCommand()` (prefix commands), and call the wrapped function exactly as the original was called: inside the same `try`, awaited only if it was awaited. If the framework has middleware that runs around every command (CommandKit middleware, Necord interceptors), wrap its `next()` there, as for discordx above. If the framework catches errors itself, report the result instead: `handlerFinished()` for interactions, `trackMessageCommand(message, { command, durationMs, failed })` for messages. * If slash and prefix commands share one function, `lens.wrap()` records only the interactions it is given and runs everything else untouched. Record the prefix side with `trackMessageCommand` where you still have the `Message`. * Prefix that comes from your database (a per-server prefix), aliases, mentions as a prefix: none of it matters to Shardlens. Pass the command’s own name after your parser has matched it. ## Start-up shapes [Section titled “Start-up shapes”](#start-up-shapes) * **Top-level `await`, or a `main()` function:** either works. Call `createShardlens` before `client.login()`. * **A `Client` subclass:** call it in the constructor, or right after `new MyClient()`. * **[Embedded mode](../../self-hosting/embedded/) with no top-level `await`** (CommonJS, or a `main()` function): start the collector and create `lens` in that function, before `client.login()`. Listeners registered earlier can’t see a local `lens`: keep it on the client and use `client.lens` inside them. * **TypeScript compiled to CommonJS** (tsc, tsup, esbuild): `require('@shardlens/discordjs')` works, and so does `require('@shardlens/collector/embedded')` on Node 24. * **`ShardingManager`, internal sharding, discord-hybrid-sharding:** see [Sharding](../sharding/). The rule is the same: once in the process that owns the `Client`. * **Settings:** read `SHARDLENS_URL` and `SHARDLENS_INGEST_KEY` however the project reads settings. If either is missing, the SDK logs one warning and records nothing. Keep them optional in your own validation: Shardlens must never be the reason a bot doesn’t start. Tip Installing with a coding agent? The [install prompt](../../getting-started/install-with-an-agent/) walks it through these choices for your project. # Custom events > Record your own product events with track(), with type-checked names and properties. Interactions, servers and bot health are recorded automatically. For anything else, such as a ticket opened, a game finished or a purchase flow started, call `track()`. tickets.ts ```ts import type { Shardlens } from '@shardlens/discordjs'; import type { ButtonInteraction } from 'discord.js'; // Register your events once for typed track() calls. Without this, any lower_snake_case name is accepted. declare module '@shardlens/discordjs' { interface CustomEvents { ticket_opened: { category: 'billing' | 'support' | 'other'; priority: number }; ticket_closed: { category: 'billing' | 'support' | 'other'; resolved: boolean }; } } declare const lens: Shardlens; export function onOpenTicket(interaction: ButtonInteraction, category: 'billing' | 'support' | 'other') { // The user ID is hashed inside your bot before anything is sent. lens.track('ticket_opened', { category, priority: 2 }, { userId: interaction.user.id, guildId: interaction.guildId }); } ``` ## Rules [Section titled “Rules”](#rules) * **Names** are lower snake case, start with a letter and are up to 64 characters: `ticket_opened`. * **Properties** are strings (up to 256 characters), finite numbers, booleans or `null`, up to 2 KB in total. Keys are up to 64 characters. * **String values pass through secret redaction**, so a token pasted into a property is replaced before it leaves your bot. Even so, never put message content, usernames or other personal data in properties. * **The user ID is optional** and is hashed in your bot, exactly like interaction users, so custom events count towards unique users without the ID leaving the process. * **Invalid events are dropped and counted** in SDK health. `track()` never throws. ## Typed events [Section titled “Typed events”](#typed-events) Without the `declare module` block, `track()` accepts any valid name and any properties. Once you register events, TypeScript checks every call: unknown names and wrong property types are compile errors. Declare them on `@shardlens/discordjs`, the package your bot depends on. Declaring them on `@shardlens/core`, where the interface lives, works too, but only where your package manager lets your code import a dependency of a dependency: pnpm doesn’t, and TypeScript then reports that the module can’t be found. ## The Events page [Section titled “The Events page”](#the-events-page) The dashboard’s **Events** page lists every custom event with its count and the number of people, breaks each event down by property, and has two builders: * **Funnels**: pick 2 to 5 steps (custom events or commands) and a window. Shardlens counts the people who did each step in order, within the window of their first step, with the conversion between steps, the median time to each step, and a breakdown by the day people entered. * **Cohorts**: pick what people started with and what counts as coming back (a specific event or command, or any activity). Shardlens groups people by the day or week they started and shows how many came back 1, 2, … periods later. ## How funnels stay private [Section titled “How funnels stay private”](#how-funnels-stay-private) Steps are linked by each person’s salted hash, inside the collector. Only counts leave it: there is no per-person view and the query API can’t return a hash. Two consequences of the privacy model: * A journey that crosses into a new [salt period](../../concepts/privacy-model/) counts as a new person, because the hash changes. With the default monthly period this only affects journeys that span the turn of a month. * Funnels and cohorts read raw events, so they cover the raw-retention window (35 days by default). Tip For funnels to work, pass `userId` in the `track()` context, as in the example above. Events without a user still count towards totals and properties. # Grafana > A ready-made Grafana dashboard for the Prometheus and OpenTelemetry exporters. The repository has a Grafana dashboard for [`@shardlens/exporter-prometheus`](../../self-hosting/exporter-only/): [`deploy/grafana/shardlens-dashboard.json`](https://github.com/Kkkermit/Shardlens/blob/main/deploy/grafana/shardlens-dashboard.json). It works the same with `@shardlens/exporter-otel` when the metrics reach Prometheus through an OpenTelemetry Collector, which gives them the same names. 1. Add the exporter to your bot and point Prometheus at it, as in [Exporter only](../../self-hosting/exporter-only/). 2. In Grafana, open **Dashboards → New → Import** and upload `shardlens-dashboard.json`. 3. At the top of the dashboard, pick your Prometheus data source (it starts on the default one) and, if Prometheus scrapes more than one bot, the **Job** of the bot to show. **All** adds up every job. To provision it instead, put the file in a folder Grafana reads dashboards from: grafana/provisioning/dashboards/shardlens.yaml ```yaml apiVersion: 1 providers: - name: shardlens type: file options: path: /var/lib/grafana/dashboards # holds shardlens-dashboard.json ``` ## What’s on it [Section titled “What’s on it”](#whats-on-it) * **Headline stats**: interactions per second, the share that failed, missed the deadline or got no response, p95 response time against the 3-second deadline, and how much of the invalid-request budget the last 10 minutes used. * **Interactions**: by command and by outcome, response-time percentiles, handler errors by class, and the slowest handlers by command. * **REST**: requests by status, the busiest routes, rate-limit waits by scope, and invalid requests by status. * **Gateway**: ping per shard, servers per shard and in total, shard state changes, servers joined and left, and the identify budget. * **Process**: event loop delay, memory, discord.js cache sizes, and your custom events. Components and modals with no command behind them are shown as `(none)`. ## Alerts worth setting [Section titled “Alerts worth setting”](#alerts-worth-setting) | Alert | PromQL | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Missed or unanswered interactions > 1% | `sum(rate(shardlens_interactions_total{outcome=~"timeout\|no_response"}[10m])) / sum(rate(shardlens_interactions_total[10m])) > 0.01` | | Invalid-request budget > 50% | `sum(increase(shardlens_rest_invalid_requests_total[10m])) > 5000` | | Shards reconnecting | `sum by (shard) (increase(shardlens_shard_events_total{state=~"reconnecting\|invalidated"}[15m])) > 3` | | The bot stopped answering scrapes | `up{job="discord-bot"} == 0` | Note A test checks that every query in the dashboard uses a metric and labels the exporter really produces, so the dashboard can’t drift from the code. # HTTP bots > Record interactions in bots that use an Interactions Endpoint URL, on Cloudflare Workers, Deno, Bun or Node. Bots that receive interactions over HTTP (an **Interactions Endpoint URL**) instead of the gateway use `@shardlens/http`. It runs on Cloudflare Workers, Deno, Bun and Node (for example with `@discordjs/core`), using Web-standard APIs only. * pnpm ```sh pnpm add @shardlens/http ``` * npm ```sh npm install @shardlens/http ``` * yarn ```sh yarn add @shardlens/http ``` * bun ```sh bun add @shardlens/http ``` * deno ```sh deno add npm:@shardlens/http ``` You need a running [collector](../../getting-started/quick-start/) and its ingest key (`slk_ingest_…`). The code on this page takes its types from `discord-api-types`; install it too if you don’t have it. ## Wrap your handler [Section titled “Wrap your handler”](#wrap-your-handler) `wrapInteractionHandler` takes the function that answers an interaction and returns one you call the same way. Your answer goes back to Discord unchanged; a handler that throws still throws. This is a whole bot in one module. It verifies Discord’s signature, answers, and records every interaction: worker.ts ```ts import { createShardlensHttp, type WaitUntilContext } from '@shardlens/http'; import type { APIInteraction, APIInteractionResponse } from 'discord-api-types/v10'; /** Worker bindings (vars and secrets), or `process.env` and `Deno.env.toObject()` on other runtimes. */ export interface Env { /** Developer Portal → General Information → Public Key. */ DISCORD_PUBLIC_KEY?: string | undefined; /** Your collector, for example `https://stats.example.com`. */ SHARDLENS_URL?: string | undefined; /** `slk_ingest_…`. Keep it in a secret. */ SHARDLENS_INGEST_KEY?: string | undefined; } const hex = (s: string) => Uint8Array.from(s.match(/../g) ?? [], (b) => Number.parseInt(b, 16)); /** Discord signs every request with Ed25519, and checks that the endpoint refuses a bad signature with 401. */ async function verified(request: Request, body: string, publicKey: string): Promise { const signature = request.headers.get('x-signature-ed25519'); const timestamp = request.headers.get('x-signature-timestamp'); if (!signature || !timestamp) return false; try { const key = await crypto.subtle.importKey('raw', hex(publicKey), { name: 'Ed25519' }, false, ['verify']); return await crypto.subtle.verify('Ed25519', key, hex(signature), new TextEncoder().encode(timestamp + body)); } catch { return false; } } // Shardlens finds `ctx` among the arguments, and sends this interaction's events through `ctx.waitUntil`. async function answer(interaction: APIInteraction, _ctx?: WaitUntilContext): Promise { if (interaction.type === 1) return { type: 1 }; // PING: answered, not recorded if (interaction.type === 2 && interaction.data.name === 'ping') { return { type: 4, data: { content: 'Pong!', flags: 64 } }; } return { type: 4, data: { content: 'Unknown command', flags: 64 } }; } /** The bot, for any runtime: Workers below, Deno, Bun and Node through their own servers. */ export function createBot(env: Env) { // Nothing runs until the first interaction: no timers, no network. const lens = createShardlensHttp({ endpoint: env.SHARDLENS_URL, apiKey: env.SHARDLENS_INGEST_KEY }); const handle = lens.wrapInteractionHandler(answer); return { lens, async fetch(request: Request, ctx?: WaitUntilContext): Promise { if (request.method !== 'POST') return new Response('Not found', { status: 404 }); const body = await request.text(); if (!(await verified(request, body, env.DISCORD_PUBLIC_KEY ?? ''))) { return new Response('Bad request signature', { status: 401 }); } return Response.json(await handle(JSON.parse(body) as APIInteraction, ctx)); }, }; } // Cloudflare Workers: secrets arrive with the first request, so the bot is created then. let bot: ReturnType | undefined; export default { fetch(request: Request, env: Env, ctx: WaitUntilContext): Promise { bot ??= createBot(env); return bot.fetch(request, ctx); }, }; ``` The same module runs on every runtime. Only the last few lines, which start the server, differ: * Cloudflare Workers The default export above is the Worker. Keep the URL in `wrangler.toml` and the two keys in secrets: wrangler.toml ```toml name = "my-bot" main = "worker.ts" compatibility_date = "2026-10-01" [vars] SHARDLENS_URL = "https://stats.example.com" ``` ```sh npx wrangler secret put DISCORD_PUBLIC_KEY npx wrangler secret put SHARDLENS_INGEST_KEY npx wrangler deploy ``` For `npx wrangler dev`, put the same two names in a `.dev.vars` file, which Git should ignore. Pass `ctx` to the wrapped handler, as the module does. Shardlens sends each interaction’s events through `ctx.waitUntil`, after your response has gone back to Discord. * Deno main.ts ```ts import { createBot } from './worker.ts'; const bot = createBot(Deno.env.toObject()); const server = Deno.serve({ port: 8787 }, (request) => bot.fetch(request)); // Send what is queued before the process stops. Deno.addSignalListener('SIGTERM', async () => { await server.shutdown(); await bot.lens.shutdown(); Deno.exit(0); }); ``` ```sh deno run --allow-net --allow-env main.ts ``` * Bun main.ts ```ts import { createBot } from './worker.ts'; const bot = createBot(process.env); const server = Bun.serve({ port: 8787, fetch: (request) => bot.fetch(request) }); // Send what is queued before the process stops. process.on('SIGTERM', async () => { await server.stop(); await bot.lens.shutdown(); process.exit(0); }); ``` ```sh bun main.ts ``` * Node + @discordjs/core Node has no built-in server for `Request` and `Response`, so this one turns each request into a `Request`. `@discordjs/core` sends what comes after the first answer: follow-ups and edits. main.ts ```ts import { createServer } from 'node:http'; import { API } from '@discordjs/core/http-only'; import { REST } from '@discordjs/rest'; import { createBot } from './worker.ts'; const bot = createBot(process.env); // Follow-ups and edits after a deferred reply: api.interactions.followUp(applicationId, token, { content }) export const api = new API(new REST().setToken(process.env.DISCORD_TOKEN ?? '')); const server = createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk); const request = new Request(`http://localhost${req.url}`, { method: req.method ?? 'GET', headers: req.headers as Record, body: req.method === 'POST' ? Buffer.concat(chunks) : null, }); const response = await bot.fetch(request); res.writeHead(response.status, Object.fromEntries(response.headers)); res.end(Buffer.from(await response.arrayBuffer())); }); server.listen(8787); // Send what is queued before the process stops. process.on('SIGTERM', async () => { server.close(); await bot.lens.shutdown(); process.exit(0); }); ``` Node 22.18 and later run `main.ts` as it is (`node main.ts`); on older versions, compile it first or use `tsx`. On Deno, Bun and Node, set `DISCORD_PUBLIC_KEY`, `SHARDLENS_URL` and `SHARDLENS_INGEST_KEY` in the environment. Then put the bot’s public URL in **Interactions Endpoint URL** in the Developer Portal. Discord checks it with a PING and with a badly signed request, which must get a `401`: the module answers both. Tip Any signature check works. Shardlens only needs the parsed interaction, after you have verified the request: it never sees the signature, the public key or the raw body. ## What it records [Section titled “What it records”](#what-it-records) For every interaction except PING, exactly the same fields as the [discord.js adapter](../../concepts/data-collected/): command, subcommand, options used, context, channel type, install type, locale, member tier, premium, the response type, and how long your answer took against Discord’s 3-second deadline. The user ID is hashed before anything is sent. The interaction token and what users type never leave your bot; nor do option values, unless you list the option in `captureOptionValues`. * **Buttons, selects and modals** are recorded by their custom ID, with numbers and IDs replaced by `*`. Buttons and selects are attributed to the command that created their message, and a command that opens a modal is linked to the modal’s submissions. * **Errors** thrown by your handler are recorded by class (never the message) and re-thrown unchanged. * **Slow answers**: a response returned more than 3 seconds after the interaction was created is recorded as a timeout, because Discord will already have shown “The application did not respond”. * **Deferred replies**: the time recorded is the time to your first answer, the deferral. Follow-ups and edits you send through Discord’s REST API afterwards are not recorded. * **`Response` objects**: a handler may return a `Response` instead of the body. Shardlens reads the callback type from a copy of a JSON body; your `Response` is returned as it is. * **Custom events**: `lens.track(name, props, { userId, guildId }, ctx)` works as in the [discord.js adapter](../custom-events/). Pass `ctx` on Workers, or the event waits for the next interaction. For [typed events](../custom-events/#typed-events), register them with `declare module '@shardlens/http'`. ## When events are sent [Section titled “When events are sent”](#when-events-are-sent) * **With `waitUntil`** (Cloudflare Workers, and anything else whose handler gets an object with a `waitUntil` method): if any argument you pass to the wrapped handler has `waitUntil`, Shardlens hashes and sends that request’s events through it, after your response. Nothing is left for a timer, because a Worker’s timers stop with the request that set them. If the collector could not be reached, the next interaction asks it for its settings again. * **Without `waitUntil`** (a long-running Node, Bun or Deno server): events are batched and sent in the background every 5 seconds, as in the discord.js adapter. Call `await lens.shutdown()` when the process stops. * **Serverless without `waitUntil`**: if your platform can stop the process as soon as the response is sent and gives you nothing like `waitUntil`, `await lens.flush()` before you return. That adds the collector’s round trip to your answer, so prefer `waitUntil` where there is one. Creating the Shardlens instance is free: nothing runs (no timers, no network) until the first interaction that is recorded, so it is safe on runtimes that forbid I/O at startup. A PING, such as Discord checking your endpoint URL, starts nothing. Note HTTP bots have no gateway, so there are no shard, server-lifecycle, REST or gateway metrics. Server and user installs can come from [webhook events](../webhook-events/) instead. ## Options [Section titled “Options”](#options) `createShardlensHttp` takes the options of the discord.js adapter that make sense without a gateway: `endpoint`, `apiKey`, `mode`, `auditIncludeProfile`, `captureOptionValues`, `normaliseCustomId`, `environment`, `release`, `optedOut`, `sampleRate`, `exporters`, `dryRun`, `logger` and `fetch`, described in [Configuration](../../getting-started/configuration/). One is its own: `instance`, a label for this deployment in SDK health (the Worker’s name, for example). Opt-outs and erasure work the same way: `lens.optOut(userId)`, `lens.optIn(userId)` and `await lens.forgetUser(userId)`. A complete Worker is in [`examples/cloudflare-worker`](https://github.com/Kkkermit/Shardlens/tree/main/examples/cloudflare-worker). # Prefix commands > Record message commands such as !ban next to slash commands, without Shardlens reading message content. Slash commands, context menus, buttons, select menus, modals and autocomplete are interactions: Shardlens records them on its own. Prefix commands (`!ban @someone`, or `@YourBot ban @someone`) are ordinary messages, so Shardlens can’t tell one from chat, and it never reads message content to find out. Your bot already knows: tell Shardlens when your own parser has matched a command. bot.ts ```ts import type { Shardlens } from '@shardlens/discordjs'; import { type Client, Events, type Message } from 'discord.js'; declare const client: Client; declare const lens: Shardlens; interface PrefixCommand { name: string; execute(message: Message, args: string[]): Promise; } declare const commands: Map; declare const aliases: Map; const PREFIX = '!'; client.on(Events.MessageCreate, async (message) => { if (message.author.bot || !message.content.startsWith(PREFIX)) return; const [typed = '', ...args] = message.content.slice(PREFIX.length).trim().split(/\s+/); const command = commands.get(aliases.get(typed.toLowerCase()) ?? typed.toLowerCase()); // Only commands your bot knows are recorded, so random text after the prefix never reaches Shardlens. if (!command) return; // Pass the command's own name, never `typed`. Shardlens doesn't read the message's content. const run = lens.wrapMessageCommand(command.name, (m: Message) => command.execute(m, args)); await run(message); }); ``` `wrapMessageCommand(command, handler)` records how long the handler took and whether it threw, then re-throws the error unchanged, like [`wrap()`](../wrapping-handlers/) does for interactions. Pass `{ command, sub, group }` instead of a name when the command has subcommands. ## If your bot catches errors itself [Section titled “If your bot catches errors itself”](#if-your-bot-catches-errors-itself) Wrap the call inside your `try`: the error passes through the wrapper, which records it, and on to your `catch`. ```ts try { await lens.wrapMessageCommand(command.name, (m: Message) => command.execute(m, args))(message); } catch { await message.reply('Something went wrong.'); } ``` Where a wrapper doesn’t fit, report the run once it is over. `failed: true` records a failure your own `catch` handled; `error` records the error’s class and Discord error code as well: ```ts const started = performance.now(); let failed = false; try { await command.execute(message, args); } catch (error) { failed = true; await message.reply('Something went wrong.'); } lens.trackMessageCommand(message, { command: command.name, durationMs: performance.now() - started, failed }); ``` ## What is recorded [Section titled “What is recorded”](#what-is-recorded) A prefix command is stored with your interactions, so the **Commands** page, unique users, servers, funnels, alerts on error rate and the Prometheus and OpenTelemetry exporters all count it. On the **Commands** page, a prefix command has a “prefix” badge, and its name has a `/` only if it also runs as a slash command. Filter or group by kind (`message_command`, shown as “Prefix command”) to see the two apart. From the message, the SDK reads the author’s ID (hashed in your bot, as for interactions), the server, the channel type, the server’s language and the author’s permissions (for the admin, manager or member split). From your call, it takes the command name, subcommand, the names of the arguments you list in `options` and, only for names in [`captureOptionValues`](../../getting-started/configuration/), their values, except any holding a Discord ID such as a mention. Never the message text, attachments, mentions or the prefix itself. The full list is on [Data collected](../../concepts/data-collected/). A message has no response deadline, no user language and no entitlements, so prefix commands are left out of the 3-second deadline figures, response time, the **Reliability** page and premium share. Their failures show on the **Commands** page and in the `error_rate` alert. Note Your bot needs the privileged Message Content intent to read prefix commands. Shardlens itself still needs only `Guilds` and never reads what it gives you. ## Slash and prefix commands that share one handler [Section titled “Slash and prefix commands that share one handler”](#slash-and-prefix-commands-that-share-one-handler) If both kinds of command end in the same function (a prefix command dressed up as an interaction, for example), you can wrap that function with `lens.wrap()`. It records interactions and passes anything else straight to your handler, so report the prefix run with `trackMessageCommand` where you still have the `Message`. Opt-outs apply to prefix commands too, and `disable: ['interactions']` turns them off along with interactions. # The /privacy command > A ready-made command for users to see what is collected, opt out, opt back in or erase their data. `createPrivacyCommand(lens)` gives you a `/privacy` command with four subcommands. Replies are ephemeral, so only the user sees them. | Subcommand | What it does | | ----------------- | --------------------------------------------------------------------------------------- | | `/privacy info` | Explains what the bot records, with a link to your privacy policy | | `/privacy optout` | Stops recording the user’s usage | | `/privacy optin` | Allows recording again | | `/privacy erase` | Deletes what was recorded about the user that the bot can still find, and opts them out | The command works in servers, in DMs with the bot and in private channels, for both server and user installs. bot.ts ```ts import { createPrivacyCommand, createShardlens } from '@shardlens/discordjs'; import { Client, Events, GatewayIntentBits, REST, Routes } from 'discord.js'; // Your own storage for opt-outs (a database table, a JSON file…). declare function loadOptOuts(): Promise; declare function saveOptOut(userId: string, optedOut: boolean): Promise; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); const lens = createShardlens(client, { endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_INGEST_KEY!, optedOut: await loadOptOuts(), // users who opted out before this restart // It may be async: a failed save is counted (see lens.on('error')), never thrown into your bot. onOptOutChange: (userId, optedOut) => saveOptOut(userId, optedOut), }); const privacy = createPrivacyCommand(lens, { policyUrl: 'https://example.com/privacy' }); // Register it with your other commands (once, from a deploy script). const rest = new REST().setToken(process.env.DISCORD_TOKEN!); await rest.put(Routes.applicationCommands(process.env.DISCORD_APP_ID!), { body: [privacy.data] }); client.on(Events.InteractionCreate, async (interaction) => { if (interaction.isChatInputCommand() && (await privacy.handle(interaction))) return; // … your other commands }); ``` Developer Policy, rule 3 Do not bypass Discord privacy and safety features; respect users who opt out or block the app. **Shardlens:** optOut(), the /privacy command, and no scraping. ## Persisting opt-outs [Section titled “Persisting opt-outs”](#persisting-opt-outs) Opt-outs live in the SDK’s memory. To keep them across restarts, save them in `onOptOutChange` and pass them back in `optedOut` when the bot starts, as above. An opted-out user’s events are dropped inside your bot, before hashing. ## Erasure from your own code [Section titled “Erasure from your own code”](#erasure-from-your-own-code) `/privacy erase` calls `lens.forgetUser()`. You can call it yourself, for example from support tooling: ```ts import type { Shardlens } from '@shardlens/discordjs'; declare const lens: Shardlens; // For example from your support tooling, after a verified erasure request. export async function eraseUser(userId: string) { lens.optOut(userId); // stop collecting in this process (persist it with onOptOutChange) const result = await lens.forgetUser(userId); // never throws; undefined if the collector couldn't be reached return result?.erased ?? 0; } ``` The collector deletes the user’s raw events, unique-user rows, install and premium rows, and in audit mode their encrypted activity. Aggregate counts are kept, because they are anonymous. Every erasure is logged. How far back it reaches depends on who can still compute the user’s hash: * **From the bot, in privacy mode**, the user’s rows are found by hash, and the bot holds only the current salt and the previous one. With a monthly or weekly salt that is every period that can still be linked to the user. With a daily salt, the days before yesterday keep their rows until their salt is destroyed, a week after each day ends; from then on nobody can link them to the user. * **From the dashboard** (**Settings → Privacy**), which takes an exact user ID, and from the bot in audit mode, the collector hashes the ID with every salt that still exists, so every period that can still be linked is erased. The `/privacy erase` reply says what was done in those terms: what the bot can link to the user was deleted, and anything older expires on its own. See the [privacy model](../../concepts/privacy-model/#opt-out-and-erasure). `forgetUser` first sends whatever the SDK still has queued, so nothing about the user arrives after the erasure. It resolves to `{ erased }`, the number of stored rows that were deleted: `0` means nothing was stored about them, or it had already expired. It resolves to `undefined` when the collector couldn’t be reached, so you can try again. Note `forgetUser` doesn’t opt the user out of future collection. Call `optOut` as well when they ask for both, as `/privacy erase` does. ## Your privacy policy [Section titled “Your privacy policy”](#your-privacy-policy) `npx shardlens privacy` prints a privacy-policy paragraph that matches your configuration, for example: ```sh npx shardlens privacy --option-values language --webhook-events --retention 35 ``` # Reports in Discord > A daily or weekly summary of your bot's numbers, posted to a Discord channel of your choice. A report is a short summary Shardlens posts to a Discord channel on a schedule, so your team sees the numbers without opening a dashboard. It goes to whichever channel you like, through that channel’s webhook. ## What a report says [Section titled “What a report says”](#what-a-report-says) ```text 📊 Daily report · Ticket Bot Wed 12 Nov (Europe/London) Commands run: 12,431 (▲ 8.2% on the day before) Unique users: 3,204 (412 new) Failed: 0.4% · Missed the 3-second deadline: 0.1% · p95 response: 412 ms Servers: 1,204 (+12 joined, −3 left) Top commands 1. /ticket · 4,210 2. /help · 2,100 3. /close · 1,870 Open in Shardlens ``` A weekly report covers the seven days before the day it is sent, and shows the average number of unique users a day. Reports contain **counts only**. No user is ever named in one, in any mode. ## Set one up [Section titled “Set one up”](#set-one-up) 1. **Create a webhook in the channel you want** In Discord: open the channel’s settings, then **Integrations → Webhooks → New Webhook → Copy Webhook URL**. The channel you create it in is the channel reports arrive in. 2. **Create the report** In the Shardlens dashboard, open **Reports** (you need to be signed in with Discord as the app owner or a team member). Give it a name, choose **Daily** or **Weekly** (and the day, for weekly), the hour, and paste the webhook URL. 3. **Try it** Press **Send now**. The report for the last finished day or week appears in your channel straight away. Times are in the time zone from **Settings → General**. You can have up to 10 reports, so different channels can get different schedules. ## Good to know [Section titled “Good to know”](#good-to-know) * **Discord webhooks only.** The URL must be `https://discord.com/api/webhooks/…` (`discordapp.com`, `canary.discord.com` and `ptb.discord.com` work too). Anything else is refused, so the collector can’t be pointed at other systems. * **Unique users are counted per UTC day.** In another time zone, a daily report shows the UTC day that overlaps your day the most. * **From the API.** `POST /v1/reports` takes the same fields as the form. `hour` is 0 to 23 in your time zone, and `weekday` is 1 for Monday to 7 for Sunday. * **Stored encrypted.** The webhook URL is encrypted with `SHARDLENS_SETTINGS_KEY` and only ever shown masked. * **One attempt per period.** If Discord refuses a report (a deleted webhook, for example), the reason is shown in the **Last sent** column and the report is tried again at its next scheduled time, not every few minutes. * **If the collector was down** at the scheduled hour, the report is sent as soon as it is back that day. Tip Want to be told the moment something breaks, rather than the next morning? That is what [alerts](../alerts/) are for. Want the numbers in your own web dashboard instead? See [Use your own dashboard](../your-own-dashboard/). # Sharding > Internal sharding, ShardingManager and discord-hybrid-sharding. Shardlens works with every common sharding setup without extra configuration. Create one Shardlens instance per discord.js `Client`, in the process where that client runs. | Setup | Where `createShardlens` goes | How events are tagged | | ----------------------- | ------------------------------------------------ | ------------------------------------ | | Internal sharding | Your bot file, once | Each event carries its guild’s shard | | `ShardingManager` | The shard file (not the manager), once per shard | The shards that process runs | | discord-hybrid-sharding | The cluster file, once per cluster | The cluster’s shard list | | Several machines | Each process | `source.instance` tells hosts apart | ## Internal sharding [Section titled “Internal sharding”](#internal-sharding) bot.ts ```ts import { createShardlens } from '@shardlens/discordjs'; import { Client, GatewayIntentBits } from 'discord.js'; // Internal sharding: one process, several shards. One Shardlens instance tags every event with its guild's shard. const client = new Client({ intents: [GatewayIntentBits.Guilds], shards: 'auto' }); createShardlens(client, { endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_INGEST_KEY!, }); await client.login(process.env.DISCORD_TOKEN); ``` ## ShardingManager [Section titled “ShardingManager”](#shardingmanager) The manager only spawns processes. Put Shardlens in the file each shard runs, exactly as in the [quick start](../../getting-started/quick-start/): manager.ts ```ts // manager.ts: one process per shard. Shardlens runs inside each shard process, not in the manager. import { ShardingManager } from 'discord.js'; const manager = new ShardingManager('./dist/bot.js', { token: process.env.DISCORD_TOKEN!, totalShards: 'auto' }); manager.on('shardCreate', (shard) => console.log(`Launched shard ${shard.id}`)); await manager.spawn(); ``` A complete example is in [`examples/sharded-bot`](https://github.com/Kkkermit/Shardlens/tree/main/examples/sharded-bot). ## discord-hybrid-sharding [Section titled “discord-hybrid-sharding”](#discord-hybrid-sharding) Each cluster runs a `Client` with several shards. Attach Shardlens in the cluster file, after setting `client.cluster`: Shardlens reads the cluster’s shard list from it. bot.ts ```ts // bot.ts: one cluster process with several shards. import { createShardlens } from '@shardlens/discordjs'; import { Client, GatewayIntentBits } from 'discord.js'; import { ClusterClient } from 'discord-hybrid-sharding'; class ClusteredClient extends Client { readonly cluster: ClusterClient; constructor() { const info = ClusterClient.getInfo(); super({ intents: [GatewayIntentBits.Guilds], shards: info.SHARD_LIST, shardCount: info.TOTAL_SHARDS }); this.cluster = new ClusterClient(this); // set before createShardlens: it reads the cluster ID and shard list } } const client = new ClusteredClient(); createShardlens(client, { endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_INGEST_KEY!, }); await client.login(process.env.DISCORD_TOKEN); ``` The complete example, with the cluster manager, is in [`examples/hybrid-sharding`](https://github.com/Kkkermit/Shardlens/tree/main/examples/hybrid-sharding). ## Stopping a sharded bot [Section titled “Stopping a sharded bot”](#stopping-a-sharded-bot) Each shard or cluster process flushes its own events, so each needs the [shutdown handler](../../getting-started/configuration/#shutting-down) for both `SIGINT` and `SIGTERM`. Ctrl+C in a terminal reaches every process, but a signal sent to the manager alone (`docker stop`, systemd, a hosting platform’s restart) does not: the shards keep running, and are killed without flushing once the manager exits. Pass the signal on from the manager, and wait for the processes to finish: manager.ts ```ts import { once } from 'node:events'; import type { ShardingManager } from 'discord.js'; declare const manager: ShardingManager; for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await Promise.all( manager.shards.map((shard) => { const child = shard.process; if (!child || child.exitCode !== null) return undefined; shard.kill(); // sends SIGTERM to the shard process return once(child, 'exit'); }), ); process.exit(0); }); } ``` With discord-hybrid-sharding (in its default `mode: 'process'`), do the same for `manager.clusters`, as in the [example’s manager](https://github.com/Kkkermit/Shardlens/tree/main/examples/hybrid-sharding/src/manager.ts): manager.ts ```ts import { once } from 'node:events'; import { Child, type ClusterManager } from 'discord-hybrid-sharding'; declare const manager: ClusterManager; for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await Promise.all( [...manager.clusters.values()].map((cluster) => { const child = cluster.thread instanceof Child ? cluster.thread.process : null; if (!child || child.exitCode !== null) return undefined; cluster.kill({ force: true, reason: signal }); // After kill(): discord-hybrid-sharding removes the process's listeners when it kills it. return once(child, 'exit'); }), ); process.exit(0); }); } ``` `lens.shutdown()` can be called twice (once for each signal): every call waits for the same flush. ## What happens across shards [Section titled “What happens across shards”](#what-happens-across-shards) * **Totals** (servers, members) add up the latest value from every shard. A shard that hasn’t reported for 2 minutes is shown as stale, not as zero. * **App-wide work** (application info, the registered command list, the gateway session budget) runs only in the process that owns shard 0, so it isn’t repeated per shard. * **No `broadcastEval`**: Shardlens never sends code between shards. * **Guild snapshots** at startup are taken per shard, so joins and removals while the bot was offline are found on every shard. Note Use the same ingest key in every process. The collector tells processes apart by host and shard. # Webhook events > Track user installs and entitlements with Discord's webhook events. The gateway tells your bot when it joins a server, but not when someone installs it to their **account** (user installs). Discord reports those, and entitlement changes, through webhook events sent to a URL you choose. Shardlens receives them on the collector, not in your bot. ## Set it up [Section titled “Set it up”](#set-it-up) 1. **Give the collector your public key** Copy **General Information → Public Key** from the [Developer Portal](https://discord.com/developers/applications) into `.env` as `DISCORD_PUBLIC_KEY`, then restart the collector. 2. **Point Discord at the collector** Under **Webhooks**, set the endpoint URL to `https://stats.example.com/v1/discord/events` and save. Discord sends a signed test request; the collector verifies it and answers. 3. **Turn on events** and subscribe to: * `APPLICATION_AUTHORIZED` and `APPLICATION_DEAUTHORIZED` (installs and removals, for servers and users) * `ENTITLEMENT_CREATE`, `ENTITLEMENT_UPDATE` and `ENTITLEMENT_DELETE` (premium) User installs then appear on the Growth page, and entitlement changes on the Premium page. For an estimated monthly revenue there, enter each subscription SKU’s monthly price under **Settings → SKU prices**: Discord sends SKU IDs, not amounts. ## How it is protected [Section titled “How it is protected”](#how-it-is-protected) * Every request is checked against your public key (Ed25519). Bad signatures and timestamps older than 5 minutes get `401`. * The collector answers `204` before doing any work, so Discord’s response deadline is never at risk. Retried deliveries are stored once. * The installing user’s ID is hashed with the current salt, exactly like the SDK does, so the same person has the same hash in both places within a salt period. The raw ID is not stored (in audit mode it is stored encrypted). Caution Discord turns webhook events off for an application whose endpoint keeps failing. If installs stop appearing, check the collector is reachable and that `DISCORD_PUBLIC_KEY` matches the application. See [Troubleshooting](../../operations/troubleshooting/). # Wrapping handlers > Measure handler time and record failures with lens.wrap(). Without any extra code, Shardlens measures how long each interaction took to get its **first response** (reply, defer, update, modal or autocomplete result), and whether Discord’s 3-second deadline was missed. That covers what users feel. Wrapping your handler adds two things: * **Handler duration**: how long your code ran, including work after the first response. * **Failures**: when the handler throws, the error class and Discord error code are recorded against the command. The error **message is never sent**, because it can contain user input or tokens. bot.ts ```ts import type { Shardlens } from '@shardlens/discordjs'; import { type Client, Events, MessageFlags } from 'discord.js'; declare const client: Client; declare const lens: Shardlens; client.on( Events.InteractionCreate, lens.wrap(async (interaction) => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'ping') { await interaction.reply({ content: 'Pong!', flags: MessageFlags.Ephemeral }); } // An error thrown here is recorded (class and Discord code, never the message) and then re-thrown unchanged. }), ); // Errors caught inside the SDK itself are counted, never thrown. Listen if you want to log them. lens.on('error', (name) => console.warn(`[shardlens] internal error: ${name}`)); ``` ## How it behaves [Section titled “How it behaves”](#how-it-behaves) * Errors are **re-thrown unchanged** after they are recorded, so your own error handling and logging still run. * The wrapper is async: it returns a promise that settles when your handler does. * If the SDK itself fails while recording, the failure is counted in SDK health and your handler is unaffected. ## If your handler already catches errors [Section titled “If your handler already catches errors”](#if-your-handler-already-catches-errors) `wrap` only sees an error that leaves the function it wraps. Many bots catch command errors themselves, to reply “something went wrong”: ```ts client.on(Events.InteractionCreate, async (interaction) => { try { await runCommand(interaction); } catch (error) { await replyWithError(interaction, error); } }); ``` Wrapping that whole listener would record every command as successful, because nothing is thrown out of it. Wrap the function inside the `try` instead, and leave your `catch` as it is: ```ts const runCommand = lens.wrap(async (interaction: ChatInputCommandInteraction) => { await commands.get(interaction.commandName)?.execute(interaction); }); ``` The error passes through `wrap`, which records it and throws it on to your `catch`. Call the wrapped function exactly as the original was called. If a listener calls your handler without `await` (`client.on('interactionCreate', (i) => { handle(i); })`), keep it that way and wrap `handle`, not the listener: turning a listener `async` changes where a failure goes, because discord.js passes a rejected listener’s error to the client’s `error` event. ## With a command handler framework [Section titled “With a command handler framework”](#with-a-command-handler-framework) Wrap the function that receives the interaction, wherever your framework calls it: ```ts client.on(Events.InteractionCreate, lens.wrap((interaction) => router.handle(interaction))); ``` Tip Wrap one top-level handler rather than every command. The command name, type and outcome are read from the interaction itself. ## Prefix commands [Section titled “Prefix commands”](#prefix-commands) `wrap` records interactions only. If a wrapped function also receives prefix commands, it runs them untouched and records nothing for them. Record those with [`wrapMessageCommand` or `trackMessageCommand`](../prefix-commands/). # Use your own dashboard > Show Shardlens numbers inside the dashboard you already have, instead of keeping two places open. Already have a web dashboard for your bot? You don’t have to send people to a second one. Everything the Shardlens dashboard shows is an answer from the collector’s API, and `@shardlens/client` asks for the same answers from your own backend. The collector keeps doing the collecting, storing and counting; you decide how it looks. ## 1. Get a read key [Section titled “1. Get a read key”](#1-get-a-read-key) Setting up from scratch, `npx shardlens init … --dashboard own` turns the Shardlens dashboard off and writes `dashboard.env` with the two settings your dashboard’s server needs, `SHARDLENS_URL` and `SHARDLENS_READ_KEY` ([Choose your setup](../../getting-started/choose-your-setup/)). With a collector that is already running, use `SHARDLENS_READ_KEY` from its `.env`, or create another key in the Shardlens dashboard under **Settings → API keys → New read key** (shown once). You can keep the Shardlens dashboard on as well as your own. A read key can run queries and nothing else: it can’t send events, change settings or see who ran a command. Server side only Call the collector from your backend, never from browser code: anything in a page can be read by whoever opens it. The collector sends no CORS headers for the same reason. The key travels with every request, so the client accepts plain HTTP to `localhost` only: from another container or machine, use the collector’s HTTPS address. ## 2. Ask for what you want to show [Section titled “2. Ask for what you want to show”](#2-ask-for-what-you-want-to-show) * pnpm `pnpm add @shardlens/client` * npm `npm install @shardlens/client` * yarn `yarn add @shardlens/client` * bun `bun add @shardlens/client` `@shardlens/client` has no dependencies and uses `fetch`, so it runs in Node.js, Bun, Deno, Cloudflare Workers and Next.js route handlers. lib/shardlens.ts ```ts // Runs on your dashboard's server. A key must never reach a browser. import { createShardlensClient, lastDays } from '@shardlens/client'; const shardlens = createShardlensClient({ endpoint: process.env.SHARDLENS_URL!, // https://stats.example.com apiKey: process.env.SHARDLENS_READ_KEY!, // slk_read_… }); // A route on your own backend, for example GET /api/stats/commands. This is a Web-standard handler, so it works as a // Next.js route handler, in Hono, on Cloudflare Workers and in Bun. export async function GET(): Promise { const { rows } = await shardlens.commands({ range: lastDays(7) }); return Response.json(rows.slice(0, 10), { headers: { 'cache-control': 'private, max-age=60' } }); } // One server's most used commands, for a per-server page in your dashboard. export function topCommandsIn(guildId: string) { return shardlens.top({ metric: 'interactions', groupBy: 'command', filters: [{ field: 'guild', value: guildId }], range: lastDays(30), limit: 10, }); } // The commands that fail in one server: errors, missed 3-second deadlines and runs that got no response. export function failingCommandsIn(guildId: string) { return shardlens.top({ metric: 'interactions', groupBy: 'command', filters: [ { field: 'guild', value: guildId }, { field: 'outcome', op: 'in', value: ['error', 'timeout', 'no_response'] }, ], range: lastDays(30), limit: 10, }); } // One command in depth, for a per-command page: outcomes, how often it deferred, subcommands, options and the servers // that use it most. It reads single events, which are kept for 35 days unless Settings says otherwise (7 to 90). export function commandDetail(name: string) { return shardlens.command(name, { range: lastDays(30) }); } // Commands per day, ready for any chart library. export function commandsPerDay() { return shardlens.series({ metric: 'interactions', interval: 'day', range: lastDays(30) }); } ``` Your front end then calls your own route (`/api/stats/commands` above) and renders the rows with whatever components and chart library you already use. Answers are typed, and a failed request throws a `ShardlensClientError` with the HTTP status and the collector’s error code. Not on JavaScript? The client is a thin layer over `POST /v1/query` with `Authorization: Bearer ` and a JSON body, which any language can send: `{ "kind": "commands", "range": { "from": "…", "to": "…" } }`. ## Who ran what [Section titled “Who ran what”](#who-ran-what) In [audit mode](../audit-mode/), your own pages can show the activity log too. That takes an **activity key** (`slk_activity_…`) instead of a read key: it reads everything a read key does, and who ran what. lib/shardlens-activity.ts ```ts // Runs on your dashboard's server, behind your own sign-in: these answers name people. import { createShardlensClient } from '@shardlens/client'; const shardlens = createShardlensClient({ endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_ACTIVITY_KEY!, // slk_activity_…: who ran what, and everything a read key reads }); // The latest failed runs in one server, with who ran each. Pass `nextBefore` back as `before` for the next page. export function failedRunsIn(guildId: string, before?: string | null) { return shardlens.activity.log({ guild: guildId, outcome: 'failed', limit: 50, before }); } // Everything one user ran, newest first: for a support ticket or an abuse report. Exact IDs only. export function runsBy(userId: string) { return shardlens.activity.log({ user: userId }); } // The most active users of the last 7 days, as counts. export function busiestUsers() { return shardlens.activity.topUsers('7d'); } ``` `npx shardlens init … --dashboard own --identify-users` creates one and puts it in `dashboard.env`; with the Shardlens dashboard on, create one under **Settings → API keys → New activity key**. The [guardrails of audit mode](../audit-mode/#guardrails) apply to a key as they do to a person: every read is written to the access log under the key’s label, a user is looked up by exact ID only, and nothing groups by user. Put these routes behind your own sign-in, for your own staff. ## What you can ask for [Section titled “What you can ask for”](#what-you-can-ask-for) Every query has a `kind`, and the client has a method named after each (`shardlens.overview()`, `shardlens.eventProps({ … })`), plus `shardlens.query({ kind, … })` for any of them. Ranges are ISO timestamps, at most 400 days apart; `lastDays(30)` makes one. | `kind` | What comes back | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `overview` | The app, runs and failures per day for the last 30 days, the server count, unique users this period, and the state of each bot process’s SDK | | `commands` | Every command: runs, change on the previous period, failure rate, p95, servers, unique users, and the kinds it ran as (`chat_input`, `message_command`, menus) | | `command` | One command in depth: runs by outcome (ok, error, missed deadline, no response), how often it deferred or took over 3 s, runs per kind, subcommands, options, channel types, member tiers, languages, top servers, latency | | `series` | A metric over time (`interval`: minute, hour, day, week or month), optionally split with `groupBy` | | `top` | The top values of one dimension: commands, servers, languages, outcomes | | `heatmap` | Hour-by-weekday counts in your time zone | | `servers`, `server` | The server list (search, sort, page) and one server’s profile | | `growth`, `audience` | Joins and leaves, retention cohorts, daily and weekly unique users | | `reliability` | Response-time percentiles, missed deadlines, errors by Discord code, REST health, shards, memory | | `gauge` | One gauge over time: `shard.ping_ms`, `shard.guilds`, `memory.rss_bytes`, `eventloop.p99_ms` and the others in the [metrics list](../../concepts/metrics/). `perShard: true` gives a line per shard | | `bursts` | Minutes in the last 14 days with several times the usual number of interactions | | `premium`, `installs` | Entitlements by SKU, user installs | | `events`, `eventProps` | Your custom events and their properties | | `funnel`, `retention` | Conversion through steps, and cohort retention | `series` and `top` take `filters`, so one server’s numbers are a filter on `guild` away, as in `topCommandsIn` above. Add a filter on `outcome` for the commands that fail there (`failingCommandsIn`), and ask for `command` to build a page per command (`commandDetail`). The full schema of every query is in the [HTTP API reference](../../reference/http-api/) and at `/openapi.json` on your collector. There is no `groupBy: 'user'` and no per-user query: that is by design, in every mode. ## Linking to Shardlens for the rest [Section titled “Linking to Shardlens for the rest”](#linking-to-shardlens-for-the-rest) The pages of the Shardlens dashboard have plain addresses, so yours can link to them instead of rebuilding them: | Address | Opens | | -------------------------------------------- | ------------------------------------------------------------------------- | | `/commands/` | One command in depth | | `/servers/` | One server: runs, top and failing commands, install history | | `/activity?guild=&outcome=failed` | Who ran into a failure in that server ([audit mode](../audit-mode/) only) | | `/activity?command=&outcome=failed` | Who ran into a failure of that command (audit mode only) | This needs the Shardlens dashboard on (`SHARDLENS_DASHBOARD=on`, the default), and the last two need a Discord sign-in there. `outcome` is `failed`, `error`, `timeout`, `no_response` or `ok`. A user ID is never part of an address. ## What you can split a metric by [Section titled “What you can split a metric by”](#what-you-can-split-a-metric-by) `groupBy` and `filters` take the dimensions the metric keeps. Asking for another one is answered with `400` and `{ "error": "invalid_query" }`, with a `message` that lists the ones you can use. | `metric` | Dimensions | | -------------------------------------------------- | --------------------------------------------------------------------------- | | `interactions` | `kind`, `command`, `sub`, `outcome`, `context`, `install`, `locale`, `tier` | | `interactions`, with `guild` in it anywhere | `guild`, `kind`, `command`, `outcome` | | `components` | `kind`, `custom_id`, `source`, `outcome`, `guild` | | `interactions.autocomplete` | `command`, `option` | | `modals.shown`, `modals.submitted` | `command` and `custom_id`; `custom_id` and `outcome` | | `interactions.errors` | `command`, `error_class` | | `rest.calls`, `rest.invalid`, `rest.ratelimits` | `method`, `route`, `status`; `status`; `scope`, `route` | | `guild.joins`, `guild.leaves`, `guild.unavailable` | `detected` | | `custom` (with `name`) | None: use `eventProps` for an event’s properties | Rollups are kept in UTC: minutes for 14 days, hours for 13 months, then days. In a time zone that isn’t a whole number of hours from UTC (India, Newfoundland, Nepal, parts of Australia), hourly points start at half past (10:30) and the heatmap’s 10:00 column counts from 10:30 to 11:30. Days older than 13 months are UTC days. Per-server numbers are kept for fewer dimensions on purpose, so the store doesn’t grow with commands × servers × everything else. ## Reading the answers [Section titled “Reading the answers”](#reading-the-answers) * **Times in a series** look like `2026-11-12T14:00:00`: the start of the bucket in the `timezone` you asked for (UTC if you didn’t), with no offset. An hour or day in which nothing happened is left out, not sent as zero. * **Intervals have limits.** `minute` series cover at most 2 days and only the last 14; `hour` series at most 31 days. * **Ranges are read in whole hours.** A range that starts at 15:20 is read from 15:00, so “the last hour” always has something in it. Ranges that start more than 13 months back are read in whole days. * **Unique users** are recounted every 5 minutes, per UTC day, and “this period” is the current salt period (a month by default). Everything else is at most a minute behind. * **Percentiles** (`p50`, `p95`, `p99`) come from a histogram with fixed buckets, so they read as the upper edge of the bucket they fall in: up to a third above the true value, never below it. * **Missed deadlines** count both a reply Discord refused as too late and an interaction that got no reply at all. * **HTTP-interaction bots** (`@shardlens/http`) have no gateway, so `servers`, `growth`, shard and REST numbers stay empty for them. Interactions, audience and custom events work the same. ## Good manners [Section titled “Good manners”](#good-manners) * **Cache.** Numbers are rolled up once a minute, so caching a response for 60 seconds loses nothing. * **Limits.** `/v1/query` allows 600 requests a minute per address and answers `429` with `Retry-After` past that. `/v1/live` keeps up to 10 streams open per address (100 in all) and answers `503` with `{ "error": "busy" }` past that: share one `live()` between your visitors instead of opening one each. * **Replace** the key if it ever leaks: put a new one (`npx shardlens keys --scope read`) in the collector’s `.env` as `SHARDLENS_READ_KEY` and restart the collector. The old one stops working then. With the Shardlens dashboard on, you can instead create a new key in **Settings → API keys**, deploy it, then revoke the old one, with no gap. ## Other ways to get the numbers out [Section titled “Other ways to get the numbers out”](#other-ways-to-get-the-numbers-out) * **Into Discord:** a [scheduled report](../reports/) posts a daily or weekly summary to a channel, and [alerts](../alerts/) tell you when something breaks. * **Into Grafana:** the [Prometheus and OpenTelemetry exporters](../grafana/) send bot-health metrics to the monitoring you already run, with or without a collector. * **Live:** `shardlens.live()` follows `GET /v1/live`, a Server-Sent Events stream of interactions per minute, p95 and shard state: `for await (const update of shardlens.live({ signal })) { … }`. # Architecture > How the SDK, the collector, PostgreSQL and the dashboard fit together. ```text ┌──────────────────────────────── Discord ────────────────────────────────┐ │ Gateway (WebSocket) REST API Webhook events │ └───────┬──────────────────────────▲─────────────────────────────┬────────┘ │ events │ calls │ HTTPS, Ed25519-signed ┌───────▼──────────────────────────┴───────────┐ │ │ Your bot process │ │ │ discord.js Client ──► Shardlens SDK │ │ │ • client + REST hooks│ │ │ • HMAC user hashing │ │ │ • bounded queue, gzip│── hashed ──┐ │ └──────────────────────────────────────────────┘ batches ▼ ▼ ┌──────────── Collector (Docker or embedded) ────────┐ │ Ingest API · Webhook receiver · Background jobs │ │ Query + live API · Dashboard (React) │ └──────────────────────────┬─────────────────────────┘ │ SQL ┌──────▼──────┐ │ PostgreSQL │ └─────────────┘ ``` ## In your bot [Section titled “In your bot”](#in-your-bot) The SDK listens to public discord.js events and REST hooks. A listener copies the fields it needs into a plain object and pushes it onto a bounded queue: no I/O and no waiting on the hot path. The user ID is hashed as the event is recorded, with the salt of the period the event falls in (HMAC-SHA-256), so in privacy mode a raw ID never waits in the queue or leaves the process. Every 5 seconds (or sooner when the queue fills) the SDK: 1. Packs up to 500 events into a batch, gzips it with `CompressionStream` and sends it with the ingest key. 2. Keeps the batch on failure and retries with jittered backoff (1 to 60 seconds). When the queue is full, the least important events are dropped first: gauges, then REST windows, then custom events, and interactions and server changes last. Every drop is counted and reported in SDK health. Note The SDK never throws into your bot, never blocks it and never installs signal handlers. Each listener is wrapped, and every failure is caught and counted. ## In the collector [Section titled “In the collector”](#in-the-collector) * **Ingest** checks the key, decompresses with a size cap (1 MB compressed, 5 MB decompressed), validates each event with zod and stores it. Retried batches are recognised by event ID and stored once. * **Webhook receiver** verifies Discord’s Ed25519 signature, answers `204` immediately and processes afterwards. * **Background jobs** run on one collector at a time (an advisory lock elects the leader): minute, hour and day rollups every minute, unique users per salt period every 5 minutes, salt creation and destruction, partition creation and retention, alerts every minute and scheduled reports. * **Query API** answers typed queries. Each query kind maps to a fixed, parameterised SQL template; there is no free-form SQL and no grouping by user. * **Live API** streams live tiles over Server-Sent Events, fed by `LISTEN/NOTIFY` so it works across collectors. * **Dashboard** is a static React app served by the collector with a strict Content Security Policy. ## In PostgreSQL [Section titled “In PostgreSQL”](#in-postgresql) Raw events go into daily partitions that are dropped whole when they expire (after 35 days by default, 7 to 90 in Settings). Charts read from rollups, all in UTC buckets. Every minute the job leader recomputes the last few minutes, and the minutes late events landed in, then the hours and days they belong to, so every chart is about a minute behind: | What | Source | Kept | Freshness | | --------------------------------------- | ---------------------- | ----------------------------------------------------- | --------------- | | Live tiles | Memory | 15 minutes | 1–5 seconds | | Minute charts | Minute rollup | 14 days | About 1 minute | | Charts of ranges up to 13 months | Hour rollup | 13 months | About 1 minute | | Older ranges | Day rollup | For good | About 1 minute | | Unique users | Counts of hashed users | Counts for good, hashes until their salt is destroyed | About 5 minutes | | Command and server details, reliability | Raw rows | Raw retention | Immediate | ## Deployment modes [Section titled “Deployment modes”](#deployment-modes) | Mode | What runs | Status | | ------------- | ------------------------------------------------------------------ | --------- | | Standard | Caddy → collector (API and dashboard) → PostgreSQL | Available | | Scaled | Several collectors behind a load balancer, one PostgreSQL | Available | | Embedded | Collector inside the bot process on in-process PostgreSQL (PGlite) | Available | | Exporter only | SDK with a Prometheus or OpenTelemetry exporter, no collector | Available | The decisions behind this design are recorded as [architecture decision records](../../contributing/adr/). # Data collected > Every field Shardlens collects, what it is for, which mode it belongs to and how long it is kept. This page is **generated from the wire format** in `@shardlens/schema`. A test fails the build if a field can be sent without being listed here, so the list is complete for the version these docs were built from. Tip Shardlens never collects message content, presence, member lists or anything that needs a privileged intent. User IDs are hashed inside your bot before they are sent, and option values are sent only for the options you allow-list. ## Reading the tables [Section titled “Reading the tables”](#reading-the-tables) Each table is one object on the wire. `envelope` is the batch around every request, `event` holds the fields every event has, and the other tables are event types (such as `interaction` or `guild_join`) or objects inside them (`actor`, `guild_info`). * **Mode**: “Both” fields are collected in privacy mode and audit mode. “Audit only” fields are sent only when both the SDK and the collector are in [audit mode](../../guides/audit-mode/). * **Personal data**: “Pseudonymous” means a salted hash that can’t be reversed once its salt is destroyed. It is still personal data under UK and EU GDPR while the salt exists. “Yes” means the field identifies a person. * **Kept**: how long the collector’s database stores it. Fields marked “Not stored” are read while the batch is processed and then dropped. Raw retention is 35 days by default and configurable from 7 to 90; after raw rows expire, aggregate counts stay: minute counts for 14 days, hourly counts for 13 months and daily counts for good. [Erasure](../../guides/privacy-command/) deletes every row that holds a person’s hash, and in audit mode their encrypted records, whatever the tables say about how long those would otherwise be kept. ## Privacy mode [Section titled “Privacy mode”](#privacy-mode) ### `envelope` | Field | What it is | Mode | Personal data | Kept | | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ------------- | ------------------------------------------------------------------- | | `v` | Wire-format major version. | Both | No | Not stored; used while processing the batch only | | `mode` | Data mode the SDK runs in (privacy or audit). | Both | No | Not stored; used while processing the batch only | | `sdk` | SDK package name and version, kept with the SDK health of the sending process. | Both | No | Latest value only | | `app` | Discord application ID, environment name and bot release. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `source` | Shard IDs and an instance label (host name and process ID) for the sending process, kept with its SDK health and its gauges. The cluster ID (discord-hybrid-sharding) is sent but not stored. | Both | No | 30 days as sent (every 30 seconds for process gauges), then deleted | | `sentAt` | When the batch was sent; used to correct clock skew. | Both | No | Not stored; used while processing the batch only | | `events` | The events in the batch. | Both | No | Not stored; used while processing the batch only | ### `event` | Field | What it is | Mode | Personal data | Kept | | -------- | ----------------------------------------------------- | ---- | ------------- | ---------------------------------------------------------------- | | `id` | UUIDv7 event ID; makes retries idempotent. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `ts` | When the event happened (epoch milliseconds). | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `weight` | Inverse sample rate, so sampled counts stay accurate. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `type` | Event type. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | ### `interaction` | Field | What it is | Mode | Personal data | Kept | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `kind` | Slash command, context menu, entry point, button, select, modal submit or autocomplete. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `command` | Command name. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `group` | Subcommand group name. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `sub` | Subcommand name. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `commandId` | Registered command ID. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `commandScope` | Whether the command is global or registered to one server. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `options` | Names of the options used. Values are not collected. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `optionValues` | Values of options the bot owner allow-listed with \`captureOptionValues\` only. Never user, channel, role, mentionable or attachment options, nor a value holding a Discord ID. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `customId` | Component or modal custom ID (for a command that opened a modal, the modal's), with secrets removed and numbers and IDs replaced by \`\*\`, or as the bot's \`normaliseCustomId\` rewrites it. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `componentType` | Component type number. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `sourceCommand` | Command that created the message a component is on. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `context` | Where it ran: server, bot DM or private channel. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `install` | Whether the app was server-installed, user-installed or both. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `guild` | Server ID (not personal data). | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `channelType` | Channel type number. Channel IDs and names are never collected. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `locale` | The user's Discord app language (not their location). | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `guildLocale` | The server's preferred language. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `memberTier` | Admin, manager, member or DM, derived from the member’s permissions. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `user` | Keyed hash of the user ID, computed inside the bot process. | Both | Pseudonymous | In unique-user counts until the salt for its period is destroyed (period end + 7 days); raw rows expire after 35 days (configurable 7–90) | | `premium` | Whether the user or server has an active entitlement. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `outcome` | ok, error, timeout (missed 3-second deadline) or no response. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `errorCode` | Discord API error code, if the response failed. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `errorClass` | Error class name the handler threw. Never messages or stack traces. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `ackMs` | Milliseconds from Discord creating the interaction to the first response. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `responseType` | Interaction callback type (for example deferred or modal). | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `deferred` | Whether the first response was a deferral. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `ephemeral` | Whether the first response was ephemeral. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `handlerMs` | Handler duration, when the handler is wrapped or reports when it finished. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `shard` | Shard that received the interaction. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | ### `message_command` | Field | What it is | Mode | Personal data | Kept | | -------------- | --------------------------------------------------------------------------------------------------------------------- | ---- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `command` | Command name as the bot defines it, after aliases. Never the text the user typed. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `group` | Subcommand group name, if the bot reports one. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `sub` | Subcommand name, if the bot reports one. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `options` | Names of the arguments the bot reports as used. Values are not collected. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `optionValues` | Values of arguments the bot owner allow-listed with \`captureOptionValues\` only. Never a value holding a Discord ID. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `guild` | Server ID (not personal data). | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `channelType` | Channel type number. Channel IDs and names are never collected. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `guildLocale` | The server's preferred language. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `memberTier` | Admin, manager, member or DM, derived from the member’s permissions. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `user` | Keyed hash of the message author’s ID, computed inside the bot process. | Both | Pseudonymous | In unique-user counts until the salt for its period is destroyed (period end + 7 days); raw rows expire after 35 days (configurable 7–90) | | `outcome` | ok or error, as the handler finished. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `errorClass` | Error class name the handler threw. Never messages or stack traces. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `errorCode` | Discord API error code, if the error came from Discord. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `handlerMs` | Handler duration, when the bot reports it. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `shard` | Shard that received the message. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | ### `interaction_error` | Field | What it is | Mode | Personal data | Kept | | ------------- | ------------------------------------------------------------------- | ---- | ------------- | ---------------------------------------------------------------- | | `interaction` | ID of the interaction event the error belongs to. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `command` | Command name. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `errorClass` | Error class name the handler threw. Never messages or stack traces. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `errorCode` | Discord API error code, if the error came from Discord. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `handlerMs` | Handler duration until it failed. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | ### `command_permissions` | Field | What it is | Mode | Personal data | Kept | | ------------ | ----------------------------------------------------------------------------- | ---- | ------------- | --------------------------------------------------------------------------------------------------- | | `guild` | Server that changed command permissions. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `command` | Command ID, or the application ID for app-wide changes. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `overwrites` | Number of permission overwrites now set. Role and user IDs are not collected. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | ### `guild_info` | Field | What it is | Mode | Personal data | Kept | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ------------- | -------------------------------------------------------- | | `guild` | Server ID. | Both | No | While the bot is installed, plus 90 days after it leaves | | `name` | Server name (rendered as plain text). | Both | No | While the bot is installed, plus 90 days after it leaves | | `icon` | Server icon hash. | Both | No | While the bot is installed, plus 90 days after it leaves | | `memberCount` | Member count when the profile was sent (on joining, after a restart and on server updates), or Discord's approximate count with \`refreshGuildCounts\`. | Both | No | While the bot is installed, plus 90 days after it leaves | | `large` | Discord's large-server flag. | Both | No | While the bot is installed, plus 90 days after it leaves | | `preferredLocale` | The server's preferred language. | Both | No | While the bot is installed, plus 90 days after it leaves | | `features` | Server feature flags such as COMMUNITY or PARTNERED. | Both | No | While the bot is installed, plus 90 days after it leaves | | `premiumTier` | Boost tier. | Both | No | While the bot is installed, plus 90 days after it leaves | | `boosts` | Number of boosts. | Both | No | While the bot is installed, plus 90 days after it leaves | | `verificationLevel` | Verification level. | Both | No | While the bot is installed, plus 90 days after it leaves | | `nsfwLevel` | NSFW level. | Both | No | While the bot is installed, plus 90 days after it leaves | | `mfaLevel` | Moderator MFA requirement. | Both | No | While the bot is installed, plus 90 days after it leaves | | `createdAt` | When the server was created. | Both | No | While the bot is installed, plus 90 days after it leaves | | `joinedAt` | When the bot joined. | Both | No | While the bot is installed, plus 90 days after it leaves | | `shard` | Shard the server is on. | Both | No | While the bot is installed, plus 90 days after it leaves | | `channelCounts` | Number of channels of each type. Never names. | Both | No | While the bot is installed, plus 90 days after it leaves | | `roleCount` | Number of roles. | Both | No | While the bot is installed, plus 90 days after it leaves | | `emojiCount` | Number of custom emojis. | Both | No | While the bot is installed, plus 90 days after it leaves | | `stickerCount` | Number of stickers. | Both | No | While the bot is installed, plus 90 days after it leaves | | `botPermissions` | The bot's permission bitfield in the server. | Both | No | While the bot is installed, plus 90 days after it leaves | ### `guild_join` | Field | What it is | Mode | Personal data | Kept | | ------------------- | ------------------------------------------------------ | ---- | ------------- | --------------------------------------------------------------------------------------------------- | | `info` | Server profile at install. | Both | No | While the bot is installed, plus 90 days after it leaves | | `detectedAtStartup` | True when the join happened while the bot was offline. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | ### `guild_update` | Field | What it is | Mode | Personal data | Kept | | ------ | ----------------------- | ---- | ------------- | -------------------------------------------------------- | | `info` | Updated server profile. | Both | No | While the bot is installed, plus 90 days after it leaves | ### `guild_leave` | Field | What it is | Mode | Personal data | Kept | | ------------------- | --------------------------------------------------------- | ---- | ------------- | --------------------------------------------------------------------------------------------------- | | `guild` | Server ID that removed the bot. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `detectedAtStartup` | True when the removal happened while the bot was offline. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | ### `guild_availability` | Field | What it is | Mode | Personal data | Kept | | ----------- | --------------------------------------------------- | ---- | ------------- | --------------------------------------------------------------------------------------------------- | | `guild` | Server ID affected by a Discord outage. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `available` | Whether the server became available or unavailable. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `shard` | Shard the server is on. Not stored. | Both | No | Not stored; used while processing the batch only | ### `guild_snapshot` | Field | What it is | Mode | Personal data | Kept | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ------------- | ------------------------------------------------ | | `shards` | Shards reporting the snapshot. | Both | No | Not stored; used while processing the batch only | | `shardCount` | Total shard count, to detect resharding. | Both | No | Not stored; used while processing the batch only | | `guilds` | Server IDs on those shards, diffed to find joins and removals while offline. Held for up to a day while a new shard layout is still reporting. | Both | No | Not stored; used while processing the batch only | ### `command_registry` | Field | What it is | Mode | Personal data | Kept | | ---------- | ----------------------------------------------------------------------------- | ---- | ------------- | ---------------------------------- | | `commands` | Registered commands (ID, name, type, scope, subcommands) to find unused ones. | Both | No | While the command stays registered | ### `shard_state` | Field | What it is | Mode | Personal data | Kept | | ------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---- | ------------- | --------------------------------------------------------------------------------------------------- | | `shard` | Shard ID. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `state` | Ready, resumed, reconnecting, disconnected, error or invalidated. discord.js 15 reports ready, resumed and disconnected. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `closeCode` | Gateway close code. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `replayed` | Events replayed on resume. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `unavailableGuilds` | Servers still unavailable when the shard became ready (discord.js 14). Not stored. | Both | No | Not stored; used while processing the batch only | ### `rest_window` | Field | What it is | Mode | Personal data | Kept | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ------------- | ---------------------------------------------------------------- | | `windowMs` | Length of the aggregation window. Not stored. | Both | No | Not stored; used while processing the batch only | | `rows` | REST call counts, retries and latency histograms by method, route and status. Routes hold route words only: IDs, invite and template codes, tokens, query strings and any other value are replaced. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `invalid` | 401, 403 and 429 counts toward the invalid-request ban threshold. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | ### `rate_limit` | Field | What it is | Mode | Personal data | Kept | | ----------------- | ---------------------------------------------------------------------------------------------- | ---- | ------------- | ---------------------------------------------------------------- | | `scope` | Scope of the rate limit a request was held back for: user, global or shared. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `global` | Whether the limit was global. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `route` | Route with route words only, as for REST calls (never the raw path, which can contain tokens). | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `method` | HTTP method. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `limit` | Request limit for the bucket. Not stored. | Both | No | Not stored; used while processing the batch only | | `retryAfter` | Milliseconds until the request may be retried. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `sublimitTimeout` | Sub-limit timeout, if any. Not stored. | Both | No | Not stored; used while processing the batch only | ### `invalid_request_warning` | Field | What it is | Mode | Personal data | Kept | | --------------- | --------------------------------------------------------------------------------------------------------------- | ---- | ------------- | ------------------------------------------------------------------- | | `count` | Invalid requests counted by discord.js in the current window, kept as the \`rest.invalid_warning_count\` gauge. | Both | No | 30 days as sent (every 30 seconds for process gauges), then deleted | | `remainingTime` | Milliseconds left in the window. Not stored. | Both | No | Not stored; used while processing the batch only | ### `gauge_window` | Field | What it is | Mode | Personal data | Kept | | -------- | ------------------------------------------------------------------------------------- | ---- | ------------- | ------------------------------------------------------------------- | | `gauges` | Process and gateway gauges: shard ping and servers, event-loop delay, memory, caches. | Both | No | 30 days as sent (every 30 seconds for process gauges), then deleted | ### `entitlement` | Field | What it is | Mode | Personal data | Kept | | ----------------- | ---------------------------------------------------------- | ---- | ------------- | --------------------------------------------------------------------------------------------------- | | `action` | Created, updated or deleted. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `sku` | SKU ID. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `entitlementType` | Entitlement type (purchase, test, subscription and so on). | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `owner` | Whether a user or a server owns the entitlement. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `user` | Keyed hash of the owning user. | Both | Pseudonymous | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `guild` | Owning server ID. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `startsAt` | Start time. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `endsAt` | End time. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | ### `subscription` | Field | What it is | Mode | Personal data | Kept | | ------------- | ----------------------------- | ---- | ------------- | --------------------------------------------------------------------------------------------------- | | `action` | Created, updated or deleted. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `status` | Subscription status. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `skus` | SKU IDs. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `user` | Keyed hash of the subscriber. | Both | Pseudonymous | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `periodStart` | Current period start. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | | `periodEnd` | Current period end. | Both | No | No automatic expiry. A user hash in it can no longer be linked to anyone once its salt is destroyed | ### `custom` | Field | What it is | Mode | Personal data | Kept | | ------- | -------------------------------------------------------------------------------------- | ---- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `name` | Custom event name passed to \`track()\`. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `props` | Properties passed to \`track()\`, chosen by the bot owner. The SDK sends at most 2 KB. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | | `user` | Keyed hash of the user, if the bot passes one. | Both | Pseudonymous | In unique-user counts until the salt for its period is destroyed (period end + 7 days); raw rows expire after 35 days (configurable 7–90) | | `guild` | Server ID, if the bot passes one. | Both | No | Raw rows 35 days (configurable 7–90), then aggregate counts only | ### `app_info` | Field | What it is | Mode | Personal data | Kept | | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ------------- | ------------------------------------------------------------------- | | `name` | Application name. | Both | No | Latest value only | | `approximateGuildCount` | Discord's approximate server count. | Both | No | 30 days as sent (every 30 seconds for process gauges), then deleted | | `approximateUserInstallCount` | Discord's approximate user-install count. | Both | No | 30 days as sent (every 30 seconds for process gauges), then deleted | | `approximateUserAuthorizationCount` | Discord's approximate user-authorisation count. | Both | No | Latest value only | | `dashboardUserIds` | The app owner's or accepted team members' user IDs, kept as they are to check a Discord sign-in to the dashboard. Admin sessions and the admin activity log keep the ID of the team member who signed in. | Both | Yes | Latest value only | | `eventWebhooksStatus` | Whether Discord webhook events are enabled. | Both | No | Latest value only | | `skus` | SKU IDs, names and types. | Both | No | Latest value only | | `sessionStartRemaining` | Identify calls left in the current 24-hour window. | Both | No | 30 days as sent (every 30 seconds for process gauges), then deleted | | `sessionStartTotal` | Identify calls allowed per 24 hours. | Both | No | Latest value only | | `nodeVersion` | Node.js version of the bot process. | Both | No | Latest value only | | `libVersion` | discord.js version of the bot process. | Both | No | Latest value only | ### `sdk_health` | Field | What it is | Mode | Personal data | Kept | | ---------------- | ----------------------------------------------- | ---- | ------------- | ----------------- | | `queueDepth` | Events waiting to be sent. | Both | No | Latest value only | | `dropped` | Events dropped, by priority lane and by reason. | Both | No | Latest value only | | `failedFlushes` | Batches that failed to send. | Both | No | Latest value only | | `internalErrors` | Errors caught inside the SDK, by name. | Both | No | Latest value only | ## Audit mode only [Section titled “Audit mode only”](#audit-mode-only) ### `interaction` | Field | What it is | Mode | Personal data | Kept | | ------- | ----------------------------------------------------------------------------- | ---------- | ------------- | ---------------------------------------------- | | `actor` | Who ran it (raw user ID, optional names). Audit mode only; encrypted at rest. | Audit only | Yes | Encrypted; 30 days by default, 90 days maximum | ### `message_command` | Field | What it is | Mode | Personal data | Kept | | ------- | ----------------------------------------------------------------------------- | ---------- | ------------- | ---------------------------------------------- | | `actor` | Who ran it (raw user ID, optional names). Audit mode only; encrypted at rest. | Audit only | Yes | Encrypted; 30 days by default, 90 days maximum | ### `actor` | Field | What it is | Mode | Personal data | Kept | | ---------- | --------------------------------------------------------------------------------------- | ---------- | ------------- | ---------------------------------------------- | | `userId` | Discord user ID of the person who ran the interaction or message command. | Audit only | Yes | Encrypted; 30 days by default, 90 days maximum | | `username` | Username. Left out with \`auditIncludeProfile: false\`. | Audit only | Yes | Encrypted; 30 days by default, 90 days maximum | | `avatar` | Avatar hash, to show the profile picture. Left out with \`auditIncludeProfile: false\`. | Audit only | Yes | Encrypted; 30 days by default, 90 days maximum | ## Copies outside the collector’s database [Section titled “Copies outside the collector’s database”](#copies-outside-the-collectors-database) * **Your own database.** With an [event sink](../../self-hosting/your-own-database/), the collector copies every event it accepts, without the fields marked “Yes” under personal data, and deletes the copies after the sink’s own retention (35 days by default). * **ClickHouse (preview).** With the [ClickHouse store](../../self-hosting/scaling/#clickhouse-preview), interactions, message commands and custom events are copied there for 35 days, whatever the raw retention setting, and their minute counts for 400 days. * **Exporters.** The [Prometheus and OpenTelemetry exporters](../../self-hosting/exporter-only/) run inside your bot. They see events before users are hashed, with the user left out, and keep only counts and timings. # Discord limits > The deadlines and rate limits Shardlens measures, and why they matter. Most bot outages users notice come from a few Discord limits. Shardlens measures each one. | Limit | Value | Where to see it | | -------------------------- | ------------------------------------------------------------- | ------------------------------------ | | First interaction response | 3 seconds | Reliability → response time | | Interaction token lifetime | 15 minutes for follow-ups | Response timing stops at 15 min | | Global REST limit | 50 requests per second per bot (interaction endpoints exempt) | Reliability → REST | | Invalid requests | 10,000 per 10 minutes per IP | Reliability → invalid-request budget | | Gateway sessions | A daily budget of identifies, shown by `GET /gateway/bot` | Reliability → identify budget | | Webhook events | `204` within 3 seconds; retried for up to 10 minutes | Growth → user installs | ## The 3-second deadline [Section titled “The 3-second deadline”](#the-3-second-deadline) Discord shows “The application did not respond” if an interaction gets no first response (reply, defer, update, modal or autocomplete result) within 3 seconds. Shardlens times each interaction from Discord’s timestamp to the first response and reports p50, p95 and p99 per command, and the share that missed the deadline. If a command is slow, defer first (`interaction.deferReply()`) and do the work afterwards. The deadline only applies to the first response. ## The invalid-request budget [Section titled “The invalid-request budget”](#the-invalid-request-budget) Every `401`, `403` and `429` response counts towards a limit of 10,000 per 10 minutes per IP address. Going over it gets the IP temporarily banned by Cloudflare, and then **every** request fails, not just the bad ones. `429`s with `X-RateLimit-Scope: shared` don’t count. Shardlens shows how much of the budget the last 10 minutes used. An [alert](../../guides/alerts/) on `invalid_requests_pct` above 50% gives you time to react. Tip The usual causes are retrying after `403 Missing Permissions` and editing messages in deleted channels. The REST table on the Reliability page shows which route the errors come from. ## Rate limits [Section titled “Rate limits”](#rate-limits) discord.js queues requests to respect rate limits, so `429`s are rare unless several processes share a token or a shared resource is busy. Shardlens records each request discord.js held back for a rate limit, by route and whether the global limit was the reason, and counts every `429` response in the REST table and the invalid-request budget. ## What Discord doesn’t tell bots [Section titled “What Discord doesn’t tell bots”](#what-discord-doesnt-tell-bots) Some numbers aren’t available to any bot: message views, why a server removed the bot, live member counts without privileged intents, and the country a user is in (`locale` is their app language). Shardlens shows what is knowable and labels approximations. # Metrics > Every metric Shardlens computes, generated from the metric registry. This page is **generated from the metric registry** in `@shardlens/schema`, the list the collector’s rollups and gauges follow. **From** names the [wire event types](../data-collected/) each metric is computed from; `webhook` means [Discord webhook events](../../guides/webhook-events/) the collector receives itself. * **Counters** are summed into minute, hour and day rollups, kept for 14 days, 13 months and for good. Two are stored as single events instead, as their descriptions say. * **Histograms** use 40 fixed buckets on a logarithmic scale from 1 ms to 60 s, so percentiles can be merged across shards and time ranges. A percentile is reported as the upper edge of the bucket it falls in: up to a third above the true value, never below it. Anything slower than 60 s lands in the last bucket and reads as about 80 s. * **Gauges** are samples, kept for 30 days. Process gauges come from every shard and process every 30 seconds: totals (`shard.guilds`, `memory.*`, `cache.*`) are added up across them, and latencies (`shard.ping_ms`, `eventloop.p99_ms`) are averaged, with the worst kept as the maximum. The `app.*` and `identify.remaining` gauges come from the process that runs shard 0, every 30 minutes. | Metric | Kind | Unit | From | Description | | ---------------------------- | ----------------- | -------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `interactions` | counter | count | `interaction`, `message_command` | Commands, context menus, entry points and message (prefix) commands run, with outcome and response-time histogram. Split by command, subcommand, kind, outcome, context, install type, locale and member tier; never by server. | | `interactions.by_guild` | counter | count | `interaction`, `message_command` | The same runs split by server, kind, command and outcome only, so the main rollup does not grow with commands × servers. | | `interactions.autocomplete` | counter | count | `interaction` | Autocomplete requests, by command and focused option. | | `components` | counter | count | `interaction` | Button and select-menu interactions, by normalised custom ID and source command. | | `interactions.errors` | counter | count | `interaction_error` | Wrapped handlers that failed after the first response, by command and error class. | | `commands.permissions` | counter | count | `command_permissions` | Servers changing who may use commands (command lockdowns). Each change is stored, but not summed into rollups or shown in the dashboard. | | `modals.shown` | counter | count | `interaction` | Interaction callbacks of type 9 (modal shown), by command. | | `modals.submitted` | counter | count | `interaction` | Modal submissions, by normalised custom ID. | | `rest.calls` | counter | count | `rest_window` | REST calls by bucketed route, method and status, with a latency histogram. | | `rest.invalid` | counter | count | `rest_window` | 401, 403 and 429 responses by status, toward Discord's ban at 10,000 invalid requests in 10 minutes. Shared 429s, which don't count toward it, are counted apart. | | `rest.ratelimits` | counter | count | `rate_limit` | 429 responses by scope (user, global, shared) and route. | | `guild.joins` | counter | servers | `guild_join`, `guild_snapshot` | Servers that added the bot, including joins detected at startup. | | `guild.leaves` | counter | servers | `guild_leave`, `guild_snapshot` | Servers that removed the bot, including removals detected at startup. | | `guild.unavailable` | counter | servers | `guild_availability` | Server outages reported by Discord (kept apart from removals). | | `shard.events` | counter | count | `shard_state` | Shard lifecycle events (ready, resumed, reconnecting, disconnected, error, invalidated), listed one by one on the Reliability page rather than summed into rollups. | | `entitlements` | counter | count | `entitlement`, `webhook` | Entitlements created, updated and deleted, by SKU, from the gateway and from Discord webhook events. | | `subscriptions` | counter | count | `subscription` | Subscriptions created, updated and deleted, by status. | | `custom.` | counter | count | `custom` | Custom events sent with \`track()\`, one metric per event name. | | `webhook.` | counter | count | `webhook` | Discord webhook events received by the collector, one metric per event type. | | `shard.ping_ms` | gauge (per shard) | ms | `gauge_window` | Gateway heartbeat latency, sampled every 30 seconds. | | `shard.guilds` | gauge (per shard) | servers | `gauge_window` | Servers on the shard. The total server count is the sum of the latest value per shard. | | `eventloop.p99_ms` | gauge | ms | `gauge_window` | Event-loop delay p99 in the bot process over the last sample window. | | `memory.rss_bytes` | gauge | bytes | `gauge_window` | Resident set size of the bot process. | | `memory.heap_used_bytes` | gauge | bytes | `gauge_window` | V8 heap in use in the bot process. | | `cache.users` | gauge | count | `gauge_window` | Size of the discord.js user cache. | | `cache.channels` | gauge | count | `gauge_window` | Size of the discord.js channel cache. | | `rest.invalid_warning_count` | gauge | count | `invalid_request_warning` | Invalid requests discord.js has counted in its current 10-minute window, from its warning event. Sent only when the bot sets discord.js's \`invalidRequestWarningInterval\`. | | `identify.remaining` | gauge | sessions | `app_info` | Remaining identify calls in the current 24-hour window (\`session_start_limit.remaining\`). | | `app.approx_guilds` | gauge | servers | `app_info` | Discord's approximate server count for the application. | | `app.approx_user_installs` | gauge | users | `app_info` | Discord's approximate user-install count for the application. | Names ending in `.` or `.` are patterns: custom events from `track()` are counted as `custom.`, and Discord webhook events as `webhook.`. The [HTTP API reference](../../reference/http-api/) lists the ones its query route serves. # Privacy model > Salted hashing, salt destruction, the two data modes and how Shardlens maps to Discord's Developer Policy. Shardlens counts **how many** people use your bot, not **who**. In privacy mode (the default), user IDs never leave your bot process. ## Hashing in your bot [Section titled “Hashing in your bot”](#hashing-in-your-bot) When an interaction arrives, the SDK replaces the user ID with: ```text h1:2026-11:3f9a1c… (version, salt period, 16 bytes of HMAC-SHA-256 as hex) ``` * **Keyed**: the hash is an HMAC with a secret salt from the collector. Without the salt, nobody can check whether a hash belongs to a given user ID, which a plain hash of a Discord ID would allow. * **Per period**: each salt period (month by default; week or day are stricter) has its own salt, so the same user has unrelated hashes in different periods. * **Truncated** to 16 bytes, enough to count without collisions. ## Salts are destroyed [Section titled “Salts are destroyed”](#salts-are-destroyed) The collector creates a salt for each period and serves it to the SDK. **Seven days after a period ends, its salt is destroyed**: the secret is deleted and that period’s unique-user table is dropped. From then on, nobody (including you) can link those hashes back to a user, or link two periods together. Your bot holds only the salts the collector currently serves: this period’s, the previous period’s until it is destroyed, and the next period’s in the last few minutes before it starts, so events at the boundary never wait. When the collector stops serving a salt, the bot forgets it at its next settings refresh, within the hour. | Salt period | Unique users you can count | Strictness | | ----------- | -------------------------- | ---------- | | Month | Daily, weekly and monthly | Default | | Week | Daily and weekly | Stricter | | Day | Daily only | Strictest | Change the period in **Settings → User identity**. ## What else stays out [Section titled “What else stays out”](#what-else-stays-out) * Message content is never collected, and no privileged intents are needed. For [prefix commands](../../guides/prefix-commands/), your bot reports the command it matched; the SDK never reads the message. * Usernames, avatars and display names are never collected in privacy mode. * Option values are recorded only for options you allow-list, and secrets are redacted before anything is sent. * Bot tokens, interaction tokens, REST paths and request headers are never sent or logged. REST calls are recorded by bucketed route only (`/channels/:id/messages`). ## Audit mode [Section titled “Audit mode”](#audit-mode) [Audit mode](../../guides/audit-mode/) adds who ran each interaction, for support and abuse handling. It has to be switched on in both the SDK and the collector, is encrypted at rest, kept for at most 90 days, and every access is logged. It is read by a person signed in with Discord, or from your own dashboard’s server with an activity key that you create for it; read keys can’t read it. ## Opt-out and erasure [Section titled “Opt-out and erasure”](#opt-out-and-erasure) Users can opt out or ask for erasure with the [`/privacy` command](../../guides/privacy-command/). Opted-out users’ events are dropped inside your bot. Erasure drops the user’s events that are still waiting to be sent, then deletes their stored rows by hash for every period whose salt the bot holds. With a monthly or weekly salt that is every period that can still be linked to them. With a daily salt, the days before yesterday keep their rows until their salt is destroyed, a week after each day ends; from then on nobody can link those rows to the user. In audit mode the bot also sends the raw ID, and the collector erases every period whose salt still exists. ## Discord Developer Policy [Section titled “Discord Developer Policy”](#discord-developer-policy) Developer Policy, rule 15 Collect only what is necessary for the functionality you describe; use aggregated or de-identified data to improve your app. **Shardlens:** Privacy mode is the default. Audit mode is framed as support and abuse-handling functionality, with guardrails. Developer Policy, rule 16 No profiling of users or their relationships. **Shardlens:** No per-user profile pages, and the query API cannot group by user. Developer Policy, rule 19 No re-identification of de-identified data. **Shardlens:** Salts are destroyed, and there is no reverse lookup in privacy mode. Developer Policy, rule 21 No AI training on message content. **Shardlens:** Message content is never collected. Rules 17 and 18 (no data brokers, no selling) hold because Shardlens is self-hosted and sends nothing to anyone but your collector. Shardlens has no telemetry of its own. ## UK and EU GDPR [Section titled “UK and EU GDPR”](#uk-and-eu-gdpr) Discord user IDs are personal data, and pseudonymised data such as salted hashes is still personal data while the salt exists. As the bot owner you are the controller: publish a privacy policy (`npx shardlens privacy` prints a paragraph matching your setup) and record your lawful basis, usually legitimate interests for usage analytics. Shardlens helps with data minimisation, retention limits, opt-out and erasure. Caution This is not legal advice. # Page not found > That page does not exist. Try the search, or start from the quick start. # Shardlens > Product analytics and bot health for discord.js, self-hosted in one command. No privileged intents. User IDs never leave your bot. Three lines in your bot `createShardlens(client, { endpoint, apiKey })`. Works with the `Guilds` intent alone, on discord.js 14.12 or later and 15. Private by construction User IDs are hashed inside your bot with a salt that rotates and is then destroyed. Message content is never collected. Bot health nobody else shows Response times against the 3-second deadline, REST latency by route, 429s, the invalid-request budget and shard health. Yours, self-hosted `docker compose up` gives you the collector, PostgreSQL and the dashboard behind HTTPS. MIT-licensed. ![The Shardlens overview page with fictional demo data: live tiles, servers, unique users and runs over 30 days](/Shardlens/_astro/overview.GQfKUSae_Z2s7DY.webp) [Quick start](getting-started/quick-start/)Run the collector, add three lines to your bot, open the dashboard. [What is collected](concepts/data-collected/)Every field, generated from the wire format, with its purpose and retention. # Backups > Backing up and restoring the collector's PostgreSQL database. Everything Shardlens stores is in PostgreSQL. Back it up with `pg_dump`, keep `.env` safe separately, and test a restore now and then. ## Daily backup [Section titled “Daily backup”](#daily-backup) From the folder with `docker-compose.yml`: ```sh docker compose exec -T postgres pg_dump -U shardlens -Fc shardlens > "shardlens-$(date +%F).dump" ``` Run it from cron, for example every night at 03:00: ```sh 0 3 * * * cd /opt/shardlens && docker compose exec -T postgres pg_dump -U shardlens -Fc shardlens > backups/shardlens-$(date +\%F).dump ``` Copy the dumps off the server and encrypt them; a backup holds hashed user IDs and, in audit mode, encrypted identities. Caution A backup without `.env` is only half a backup. Alert webhooks need `SHARDLENS_SETTINGS_KEY` and audit-mode data needs `SHARDLENS_AUDIT_KEY` to be readable after a restore. ## Restore [Section titled “Restore”](#restore) 1. Stop the collector so nothing writes during the restore: ```sh docker compose stop collector ``` 2. Restore into a clean database: ```sh docker compose exec -T postgres dropdb -U shardlens shardlens docker compose exec -T postgres createdb -U shardlens shardlens docker compose exec -T postgres pg_restore -U shardlens -d shardlens < shardlens-2026-11-13.dump ``` 3. Start the collector with the same `.env`: ```sh docker compose start collector ``` ## Test your restores [Section titled “Test your restores”](#test-your-restores) Once a month, restore the latest dump into a scratch PostgreSQL container and open the dashboard against it. A backup you have never restored is a hope, not a backup. ## Privacy and backups [Section titled “Privacy and backups”](#privacy-and-backups) Erasure and salt destruction delete data from the live database, not from old backups. Keep backups only as long as you need them (for example 30 days), so erased data and destroyed salts age out of them too. # FAQ > Common questions about Shardlens. ## Does Shardlens need privileged intents? [Section titled “Does Shardlens need privileged intents?”](#does-shardlens-need-privileged-intents) No. Everything works with `GatewayIntentBits.Guilds`. Shardlens never reads message content, presences or member lists. ## Will it slow my bot down? [Section titled “Will it slow my bot down?”](#will-it-slow-my-bot-down) The SDK adds under 50 µs of CPU per interaction and stays under 15 MB of memory at the default 10,000-event buffer. A benchmark in CI fails the build if that regresses. Listeners never do I/O; sending happens in the background every 5 seconds. ## What happens when the collector is down? [Section titled “What happens when the collector is down?”](#what-happens-when-the-collector-is-down) The SDK keeps events in its bounded queue and retries with backoff. For a bot that was already running, a five-minute outage loses nothing (this is tested). For longer outages, the least important events are dropped first and the drops are counted, unless you turn on the [disk spool](../../getting-started/configuration/#disk-spool), which keeps them on disk (100 MB by default) across outages and restarts and sends them once the collector is back. A bot that **starts** while the collector is down is different: it has not yet been given the salt it hashes user IDs with, and it will not send an ID unhashed. It holds up to 1,000 events for 60 seconds, then drops them and says so once in its log (`stats().dropped.salt_missing` counts them). Recording starts as soon as the collector answers. ## Can I see who used a command? [Section titled “Can I see who used a command?”](#can-i-see-who-used-a-command) Not in privacy mode, by design: user IDs never leave your bot. If you need it for support or abuse handling, turn on [audit mode](../../guides/audit-mode/), which has to be switched on in both the SDK and the collector and comes with guardrails. ## How are unique users counted without user IDs? [Section titled “How are unique users counted without user IDs?”](#how-are-unique-users-counted-without-user-ids) Each user ID is replaced with a salted hash inside your bot. The same user has the same hash for the whole salt period (a month by default), so the collector can count distinct hashes. See the [privacy model](../../concepts/privacy-model/). ## Does Shardlens send anything to you? [Section titled “Does Shardlens send anything to you?”](#does-shardlens-send-anything-to-you) No. Shardlens has no telemetry. Your bot talks to your collector and nothing else. ## Does it work with sharding? [Section titled “Does it work with sharding?”](#does-it-work-with-sharding) Yes: internal sharding, `ShardingManager`, discord-hybrid-sharding and several machines. See [Sharding](../../guides/sharding/). ## Which discord.js versions does it support? [Section titled “Which discord.js versions does it support?”](#which-discordjs-versions-does-it-support) 14.12 or later, and 15. Earlier 14.x releases use version 1 of discord.js’s REST client, whose response events Shardlens reads response times and REST health from, so the package’s peer range starts at 14.12. A few fields need a newer release: the interaction context, user installs and the command a button came from need 14.16, and subscriptions 14.17. On older releases those fields are left out. ## Does it work with discord.js 15? [Section titled “Does it work with discord.js 15?”](#does-it-work-with-discordjs-15) Yes. The adapter supports discord.js 14 and 15 through public APIs only, and a nightly CI job runs its tests against the latest discord.js release and the v15 development builds, which its peer range accepts. discord.js 15 needs Node 24.17 or later. Its gateway reports fewer shard states: ready, resumed and disconnected (with the close code), but not reconnecting, invalidated or the servers still unavailable at ready. ## Why is the server count different from Discord’s? [Section titled “Why is the server count different from Discord’s?”](#why-is-the-server-count-different-from-discords) Discord’s application count is approximate and can lag. Shardlens counts servers from gateway events and checks the difference; the Growth page shows the drift. ## Is it free? [Section titled “Is it free?”](#is-it-free) Yes. Shardlens is MIT-licensed. You pay only for the server you run the collector on. ## Is this affiliated with Discord? [Section titled “Is this affiliated with Discord?”](#is-this-affiliated-with-discord) No. Shardlens is not affiliated with or endorsed by Discord. # Security > The threat model in brief, and how to report a vulnerability. ## Reporting a vulnerability [Section titled “Reporting a vulnerability”](#reporting-a-vulnerability) Please **don’t** open a public issue. Report it privately on GitHub: **Security → Report a vulnerability** on the [Shardlens repository](https://github.com/Kkkermit/Shardlens/security). You should get an acknowledgement within 7 days. The full policy is in [`SECURITY.md`](https://github.com/Kkkermit/Shardlens/blob/main/SECURITY.md). ## Threat model [Section titled “Threat model”](#threat-model) | Threat | Controls | | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Bot token leaks through the SDK | REST options and headers are never serialised; only bucketed routes are stored; secret redaction on all error text; fuzz-tested with 10,000 token-shaped strings | | Interaction or webhook tokens leak | Paths are read in memory only to find the interaction ID; stored routes contain `:token`, never the token | | Forged ingest traffic | 32-byte bearer keys stored only as SHA-256 hashes, scoped (ingest or read), checked before the request body is read, HTTPS only | | Request floods and scanning | Every route is rate limited per client address, unknown paths included; sign-in, key and export routes have tighter limits | | Forged Discord webhook events | Ed25519 verification, 5-minute timestamp window, `401` on failure | | Hostile payloads | zod validation on every route, 1 MB compressed and 5 MB decompressed limits, field length caps; NUL characters, IDs beyond 64 bits and anything else the database would refuse are answered with 400, never 500 | | Slow or stalled requests | A client has 30 seconds to send a request (60 for its headers); a client that disconnects early costs nothing | | SQL injection | Parameterised queries only; queries use enums, never identifiers from input | | XSS from server names or usernames | Rendered as text only, and a strict Content Security Policy | | CSV formula injection | Exported cells starting with `= + - @`, tab or carriage return are neutralised | | Cross-site requests | `SameSite=Lax` cookies and a required CSRF header on every change | | Session theft | `HttpOnly` and `Secure` cookies, hashed session IDs, 7-day expiry, rotation on sign-in, server-side sign-out. Revoking a read key ends the sessions opened with it; an admin taken off the team loses access on their next request | | Unauthorised dashboard access | Full access only for the application owner, team and listed extras; OAuth state and PKCE | | SSRF through alert and report webhooks | Only Discord webhook URLs are accepted, redirects are refused, and the URLs are stored encrypted | | Re-identification of hashes | HMAC with secret salts that are destroyed after their period | | Audit data exposure | AES-256-GCM with a key outside the database, 90-day maximum retention, access log, exact lookups only | | Database exposure | PostgreSQL is not published by Docker Compose | | The SDK harming the bot | Bounded queue, priority dropping, no I/O in listeners, timers that don’t keep the process alive, chaos tests | | Supply chain | Zero-dependency core, lockfile, Renovate, npm provenance, CodeQL, dependency review, OpenSSF Scorecard | | Container escape | Non-root user that can’t change the collector’s files, read-only root filesystem, no Linux capabilities | ## Rate limits [Section titled “Rate limits”](#rate-limits) Limits are per client address, per minute. Past a limit the collector answers `429` with a `Retry-After` header, which the SDK honours. | Route | Limit | | ----------------------------------------------------------------------------------- | ----- | | `POST /v1/ingest` | 3,000 | | `POST /v1/query`, `POST /v1/discord/events` | 600 | | `GET /v1/config`, `GET /v1/badge/*` | 120 | | `POST /v1/privacy/erase` | 60 | | `/auth/discord`, `/auth/read-key` | 20 | | `GET /v1/audit/export.csv`, `POST /v1/alerts/:id/test`, `POST /v1/reports/:id/send` | 10 | | Everything else, including unknown paths | 1,200 | Behind a reverse proxy Set `SHARDLENS_TRUST_PROXY` to the number of proxies in front of the collector (`1` for Caddy, one load balancer or a platform router; the bundled Docker Compose file sets it). Otherwise every visitor appears to come from the proxy’s address and shares one limit. Avoid `true` unless your proxy replaces `X-Forwarded-For`: a proxy that adds to it lets a visitor choose the address their limits are counted under. ## If you are breached [Section titled “If you are breached”](#if-you-are-breached) Discord’s Developer Policy requires you to notify Discord and affected users of unauthorised access to API data. The [incident checklist in `SECURITY.md`](https://github.com/Kkkermit/Shardlens/blob/main/SECURITY.md#incident-checklist-for-maintainers-and-self-hosters) lists what to rotate and who to tell. Tip Rotate keys from the dashboard (**Settings → API keys**): create the new key, deploy it to your bot, then revoke the old one. Without the dashboard, put a new key in the collector’s `.env` (or delete its line from an embedded collector’s `secrets.json`) and restart the collector: the key it replaces stops working. # Troubleshooting > Fixes for no data, missing salts, 401s from the collector and webhook events being turned off. Start with `doctor` from your bot’s folder. It checks the things below in order: ```sh npx shardlens doctor --url https://stats.example.com --key slk_ingest_… ``` ## No data on the dashboard [Section titled “No data on the dashboard”](#no-data-on-the-dashboard) 1. **Is the SDK attached before login?** Call `createShardlens(client, …)` before `client.login()`. 2. **Is it sending?** Read the bot’s own log first: the SDK prints one line starting with `Shardlens:` per problem (it can’t reach the collector, the key was rejected, the URL isn’t HTTPS). Then check `lens.stats()`: `ready` should be `true`. If it stays `false`, the SDK never got its settings from the collector, which means a wrong URL or a wrong key; `failedFlushes` does not move in that case, because nothing was ever sent. Once `ready` is `true`, `failedFlushes` should not keep growing and `queueDepth` should stay low. 3. **Is it a dry run?** `dryRun: true` prints events instead of sending them. 4. **Has anything happened yet?** The Overview shows interactions. Run a command in a server with the bot. 5. **Is the time range right?** Charts use the time zone in **Settings → General**. ## `401` from the collector [Section titled “401 from the collector”](#401-from-the-collector) The key was not accepted. * Use the **ingest** key (`slk_ingest_…`) in your bot. Read keys can’t send events. * Check for a revoked key under **Settings → API keys**. * Check the bot’s environment has the full key, with no quotes or whitespace around it. ## `403` from the collector [Section titled “403 from the collector”](#403-from-the-collector) The batch is for a different application. `SHARDLENS_APP_ID` on the collector has to match the bot’s application ID. From your own dashboard, `403` with `activity_key_required` means a read key asked for who ran what: that takes an [activity key](../../guides/audit-mode/#read-it-from-your-own-dashboard). `404` with `audit_mode_off` means the key is right and the collector isn’t in audit mode. ## The collector’s address shows `"dashboard":"off"` [Section titled “The collector’s address shows "dashboard":"off"”](#the-collectors-address-shows-dashboardoff) The collector was set up without the Shardlens dashboard (`SHARDLENS_DASHBOARD=off`, from `shardlens init --dashboard own` or `none`), so it answers as an API only. Set `SHARDLENS_DASHBOARD=on` in its `.env` and restart it to get the dashboard back: [Choose your setup](../../getting-started/choose-your-setup/#changing-your-mind). ## “Salt missing” or events waiting [Section titled ““Salt missing” or events waiting”](#salt-missing-or-events-waiting) The SDK hashes user IDs with a salt from the collector’s `/v1/config`. Until it has a salt, it holds events for up to 60 seconds (1,000 events at most) and then drops them, counting the drops. If this keeps happening: * Check the bot can reach the collector (`doctor` reports **Salt available**). * Check the collector’s logs for database errors: salts are created by the collector. ## `413` or `503` from the collector [Section titled “413 or 503 from the collector”](#413-or-503-from-the-collector) * `413`: a batch was too large. The SDK splits batches automatically; if you see this, lower `maxBatchSize`. * `503`: the collector is busy. The SDK waits for `Retry-After` and retries, so no events are lost while the queue has room. ## Alerts or reports don’t arrive [Section titled “Alerts or reports don’t arrive”](#alerts-or-reports-dont-arrive) The alert history (**Alerts**) and the **Last sent** column of **Reports** say why: * `discord returned 404`: the webhook was deleted. Create a new one and save the alert or report again. * `could not reach Discord (…)`: the collector can’t connect to `discord.com`. The code says why, for example `ENOTFOUND` (no DNS) or `ECONNREFUSED`; a firewall that only allows inbound traffic is the usual cause. * `The saved webhook could not be decrypted`: `SHARDLENS_SETTINGS_KEY` changed. Save the webhook again. ## Webhook events stopped [Section titled “Webhook events stopped”](#webhook-events-stopped) Discord turns webhook events off when the endpoint keeps failing. 1. Check `DISCORD_PUBLIC_KEY` matches **General Information → Public Key**. 2. Check `https://stats.example.com/v1/discord/events` is reachable from the internet. 3. In the Developer Portal, save the endpoint URL again and turn events back on. ## Can’t sign in with Discord [Section titled “Can’t sign in with Discord”](#cant-sign-in-with-discord) * The redirect in the Developer Portal must be exactly `https://stats.example.com/auth/discord/callback`, matching `SHARDLENS_PUBLIC_URL`. * Only the application owner, team members and IDs in `SHARDLENS_EXTRA_ADMINS` get in. Others can use the read key. ## Collector won’t start [Section titled “Collector won’t start”](#collector-wont-start) The log names each invalid variable. The usual causes are a short `SHARDLENS_SESSION_SECRET` (32 characters minimum), a `SHARDLENS_SETTINGS_KEY` that isn’t 32 base64 bytes, or only one of `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET`. Tip Still stuck? Open a [GitHub discussion](https://github.com/Kkkermit/Shardlens/discussions) with the `doctor` output. Never paste keys, tokens or `.env`. ## Reading the collector’s logs [Section titled “Reading the collector’s logs”](#reading-the-collectors-logs) The collector writes one JSON object per line (`docker compose logs collector`). Every line has a `level` (30 info, 40 warning, 50 error), a `time` and a `msg`. For a readable view, pipe them through [`pino-pretty`](https://github.com/pinojs/pino-pretty): `docker compose logs -f --no-log-prefix collector | npx pino-pretty`. | Message | Level | What it means | | ---------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Shardlens collector started` | info | Startup finished. Lists the database migrations this start applied (`migrationsApplied`, empty when the database was up to date), which optional features are switched on (Discord sign-in, webhook events, audit key, ClickHouse, the sink to your own database), whether the dashboard is served, and the mode users are recorded in (`mode`, and `modeFrom`: `environment` when `SHARDLENS_MODE` set it). | | `Server listening at …` | info | The address the collector accepts connections on. | | `shutting down` | info | The collector received `SIGTERM` or `SIGINT` and is finishing what it was doing. | | `Demo mode: …` | warning | `SHARDLENS_DEMO` is on: the dashboard is open to anyone. For demo data only. | | `Live tiles are not shared …` | warning | PostgreSQL refused `LISTEN` at startup, so with several collectors each one’s live tiles show only its own traffic until a retry in the background succeeds. | | `Live tiles lost their LISTEN connection …` | warning | The connection that shares live tiles broke (a database restart, say). The collector subscribes again, waiting up to 30 seconds between tries. | | `this collector is now the job leader` | info | This instance runs the background jobs (rollups, alerts, retention). Exactly one instance does. | | `events rejected` | warning | A batch was accepted but some events were dropped. `reasons` counts them: `too_old` (older than your raw-data retention: 35 days unless Settings says otherwise), `in_future` (more than a day ahead), `unknown_salt_period` (hashed with a salt that was destroyed), `invalid_event`, `refused_by_database` (a value PostgreSQL would not store). | | `input refused by the database` | warning | A request carried a value PostgreSQL would not store. It was answered with `400`; nothing was saved from it. | | `clock skew corrected for batch` | warning | The bot’s clock is more than 5 minutes off. Timestamps were corrected; fix the clock (NTP). | | `Discord sign-in failed` | warning | The OAuth exchange failed. `reason` names the error, usually a wrong client secret or redirect URL. | | `Discord sign-in refused: …` | warning | Someone who is not the application owner, a team member or an extra admin tried to sign in. If it says the bot has not reported yet, start the bot with Shardlens once, or add your user ID to `SHARDLENS_EXTRA_ADMINS`. | | `No ingest key: …` | warning | No ingest key exists, in the environment or created in the dashboard. Set `SHARDLENS_INGEST_KEY`. | | `No way to open the dashboard: …` | warning | Neither a read key nor Discord sign-in is set up. Set `SHARDLENS_READ_KEY`. | | `No read key, and the dashboard is off: …` | warning | `SHARDLENS_DASHBOARD=off` and no read or activity key exists, so neither your own dashboard nor a script can read the numbers. Set `SHARDLENS_READ_KEY`. | | `Discord sign-in works once …` | warning | Only Discord sign-in is set up and the bot hasn’t reported yet. Set a read key or `SHARDLENS_EXTRA_ADMINS` meanwhile. | | `live update failed` | warning | The live tiles could not read the database. Logged once per open dashboard. | | `slow job` | info | A background job took more than 10 seconds. Frequent on a healthy database means it needs more resources. | | `request failed` | error | A request hit an unexpected error. `reqId` matches the `requestId` in the `500` response the caller received. | | `job failed` | error | A background job threw. `job` names it; it runs again on its next schedule. `partitions in use` means a long query kept a table locked for 2 seconds while retention dropped old data: it tries again a minute later instead of holding ingest up. | | `rows the database could not aggregate were skipped` | error | A rollup statement refused its data (a sum out of range). `skipped` names the statement and window; every other metric was still rolled up. | | `webhook event processing failed` | error | A Discord webhook event was acknowledged but could not be stored. | | ` sink … failed: …` | warning | The copy of events in [your own database](../../self-hosting/your-own-database/) could not be set up or written (`component: sink`). Logged at most once a minute, with any password removed; copies wait in memory and are retried. | | ` sink is behind: …` | warning | Your database was down or slow for long enough that 20,000 copies were waiting, so newer ones were dropped. The count is in the message. | | `ClickHouse insert failed …` | warning | The [ClickHouse](../../self-hosting/scaling/#clickhouse-preview) copy could not be written (`component: clickhouse`). Rows wait in memory and are retried; the count of dropped rows is in the message. | | `leader election failed` | error | This instance could not check the job lock. It retries every 30 seconds. | Logs never contain keys, tokens, cookies, request bodies or user IDs. Per-request lines (“incoming request”) contain URLs, so they are only written when `LOG_LEVEL` is `debug` or `trace`. That includes requests the collector turned away: a `401` for a wrong key, a `403`, a `429` for a caller over its limit. At the default level those are not logged at all, so a bot with a wrong key shows up in the bot’s log (`Shardlens: the collector rejected the API key`), not in the collector’s. In your bot, the SDK logs through `console` (or the `logger` you pass) with a `Shardlens:` prefix, once per problem rather than once per event, and `lens.on('error', …)` and `lens.stats()` expose everything it counted. # CLI > The shardlens command-line tool — init, keys, privacy and doctor. The `shardlens` package is a small CLI for setting up and checking an install. It needs Node.js 22.12 or newer and has no dependencies. Run it with `npx`, no installation needed: ```sh npx shardlens [options] ``` Or install it with `npm install --global shardlens` and run `shardlens `. `shardlens --help` lists the commands and their options, and `shardlens --version` prints the version. Each command accepts only its own options: a misspelt option, or one that belongs to another command, is refused rather than ignored. The CLI never asks questions, so it works the same in scripts and CI. | Exit code | Meaning | | --------- | --------------------------------------------------------------------------------------------------- | | `0` | Done. For `doctor`: no check failed (checks it couldn’t run are warnings). | | `1` | It failed: `init` found its files already there or couldn’t write them, or a `doctor` check failed. | | `2` | Wrong usage: an unknown command or option, a missing or invalid value. Nothing was changed. | ## `init` [Section titled “init”](#init) Writes the [Docker Compose deployment](../../self-hosting/docker-compose/) into a folder: | File | What it is | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `docker-compose.yml` | Caddy, the collector and PostgreSQL. The collector image is `ghcr.io/kkkermit/shardlens-collector:1`, the current major version; set `SHARDLENS_IMAGE` in `.env` to run another. | | `Caddyfile` | HTTPS for your domain, with a certificate Caddy gets on its own. | | `.env` | The collector’s settings, with a generated database password, session secret, settings key, ingest key and read key. Only you can read it (mode `600`). | | `bot.env` | The two settings your bot needs: `SHARDLENS_URL` and `SHARDLENS_INGEST_KEY` (the same key as in `.env`). Mode `600`. | | `dashboard.env` | With `--dashboard own` only: what the server of your own dashboard needs, `SHARDLENS_URL` and `SHARDLENS_READ_KEY`, and `SHARDLENS_ACTIVITY_KEY` with `--identify-users`. Mode `600`. | ```sh npx shardlens init --domain stats.example.com --app-id 123456789012345678 ``` | Option | Meaning | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--domain ` | The collector’s hostname, such as `stats.example.com`, without `https://`. Caddy gets a certificate for it. Required. | | `--app-id ` | Your Discord application ID (17 to 20 digits, under General Information in the Developer Portal). Required. | | `--dir ` | Where to write the files. Default `./shardlens`; created if needed. | | `--dashboard ` | Where you will look at the numbers ([Choose your setup](../../getting-started/choose-your-setup/)). `shardlens` (default): the collector serves the Shardlens dashboard. `own`: no dashboard page (`SHARDLENS_DASHBOARD=off`), and `dashboard.env` for a dashboard of your own. `none`: no dashboard page; the collector is an API only. | | `--identify-users` | Also create `SHARDLENS_AUDIT_KEY`, so you can switch from hashed to [identified users](../../guides/audit-mode/) in Settings. Without it the key is written commented out. With `--dashboard own` or `none` there is no Settings page, so it also writes `SHARDLENS_MODE=audit` and an activity key to read who ran what, and the next steps remind you to switch the bot to audit mode too. | | `--force` | Replace the files that are already there. An existing `.env` keeps its secrets (see below). | `init` prints where it wrote the files and what to do next, never a secret: ```text Wrote docker-compose.yml, Caddyfile, .env and bot.env to /home/me/shardlens Next: 1. Point DNS for stats.example.com at this server, open ports 80 and 443, then start the collector: cd /home/me/shardlens && docker compose up -d 2. Copy the two lines in bot.env to where your bot runs, then delete bot.env. 3. Run "npx shardlens doctor" in your bot's folder to check the connection. 4. Open https://stats.example.com and sign in with SHARDLENS_READ_KEY from .env. Keep a copy of .env somewhere safe: without its keys, the collector's encrypted data can't be read. ``` `.env` also lists the optional settings, empty: `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` for [Discord sign-in](../../self-hosting/docker-compose/#discord-sign-in), `DISCORD_PUBLIC_KEY` for [webhook events](../../guides/webhook-events/) and `SHARDLENS_SINK_URL` for [your own database](../../self-hosting/your-own-database/). Every variable is in the [environment reference](../environment/). ### Running `init` again [Section titled “Running init again”](#running-init-again) `init` refuses when any of the files it would write is already in the folder, so it never overwrites a project’s own `docker-compose.yml` or a running collector’s `.env` by accident. With `--force` it replaces `docker-compose.yml`, `Caddyfile` and `bot.env`, and updates an existing `.env` in place instead of replacing it: * it sets `SHARDLENS_DOMAIN`, `SHARDLENS_PUBLIC_URL` and `SHARDLENS_APP_ID` from the options; * it generates any of the database password, session secret, settings key, ingest key and read key that is missing or empty, and new ingest and read keys when the application ID changes (keys belong to one application); * with `--identify-users`, it adds `SHARDLENS_AUDIT_KEY` if there is none; * it changes `SHARDLENS_DASHBOARD` only when `--dashboard` is given, so running it again never brings back a dashboard you turned off; * it keeps every other line as it was: the existing secrets, your own settings and the comments. So `init --force` is safe on a collector that is already running, for example to change its domain or to get the compose file of a newer CLI. It prints which variables it set (`Set SHARDLENS_DOMAIN and SHARDLENS_PUBLIC_URL in the existing .env and kept everything else in it.`). A new database password would lock the collector out of its database, and a new settings or audit key would make its encrypted data unreadable, so to start from scratch delete the folder and the Docker volumes (`docker compose down -v`) instead. ## `keys` [Section titled “keys”](#keys) Prints a new API key on standard output, and nothing else there, so you can capture it in a script. A hint goes to standard error. ```sh npx shardlens keys --scope read ``` | Option | Meaning | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--scope ingest \| read \| activity` | The kind of key. Default `ingest`. An activity key reads what a read key does, and [who ran what](../../guides/audit-mode/#read-it-from-your-own-dashboard) in audit mode. | Put it in the collector’s `.env` as `SHARDLENS_INGEST_KEY`, `SHARDLENS_READ_KEY` or `SHARDLENS_ACTIVITY_KEY` and restart the collector, which stores only a hash of it. The key the variable held before stops working then, which is how a leaked key is replaced when the collector runs without the dashboard. To switch without a gap, create the new key in the dashboard under **Settings → API keys** instead, move everything to it, then revoke the old one there. ## `privacy` [Section titled “privacy”](#privacy) Prints a privacy-policy paragraph that matches your configuration, to start your bot’s privacy policy from. It is not legal advice (a reminder of that goes to standard error). ```sh npx shardlens privacy --option-values language --webhook-events ``` | Option | Meaning | | -------------------------- | ------------------------------------------------------------------------------------------- | | `--audit` | You use [audit mode](../../guides/audit-mode/) (identified users). | | `--ids-only` | Audit mode without usernames and avatars (`auditIncludeProfile: false`). Implies `--audit`. | | `--option-values ` | The option names in `captureOptionValues`, comma-separated. | | `--webhook-events` | You receive Discord [webhook events](../../guides/webhook-events/) (installs and removals). | | `--retention ` | Your raw-data retention in Settings, 7 to 90. Default 35. | | `--audit-retention ` | Your audit retention in Settings, 1 to 90. Default 30. Implies `--audit`. | The paragraph says what is recorded about a person (which command, button or menu, when, in which server, their Discord app language, whether they are an admin, a manager or a member there, server or user install, premium, whether it worked and how quickly), that option values are not recorded except the ones you list, how user IDs are pseudonymised or, in audit mode, encrypted and for how long, how long detailed records are kept, and how to opt out or ask for erasure. [What is collected](../../concepts/data-collected/) has every field. ## `doctor` [Section titled “doctor”](#doctor) Checks your setup and prints one line per check: `✓` passed, `✗` failed, `!` couldn’t be checked. ```sh npx shardlens doctor --url https://stats.example.com --key slk_ingest_… ``` | Option | Meaning | | ------------- | --------------------------------------------------------------- | | `--url ` | The collector. Default `SHARDLENS_URL`. | | `--key ` | An ingest key (`slk_ingest_…`). Default `SHARDLENS_INGEST_KEY`. | Without the options and variables, `doctor` reads `SHARDLENS_URL` and `SHARDLENS_INGEST_KEY` from a `.env` in the current folder, so in your bot’s folder it needs no options. In the folder `init` wrote, it uses the collector’s own `.env`: `SHARDLENS_PUBLIC_URL` and the same ingest key. It says which settings it took from the file, and never changes your environment or prints the key. ```text Using SHARDLENS_URL and SHARDLENS_INGEST_KEY from /home/me/my-bot/.env ✓ Node.js version: v24.11.1 (the SDK needs 22.12 or newer) ✓ discord.js: 14.22.1 ✓ Collector URL: https://stats.example.com ✓ Collector reachable: healthy ✓ Ingest key: accepted for application 123456789012345678 ✓ Data mode: privacy mode, salts rotate every month ✓ Salt available: yes ``` | Check | What it checks | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Node.js version | The Node.js running `doctor` is 22.12 or newer. | | discord.js | The discord.js installed in the current folder (or a folder above it) is 14.12 or newer, or 15. A project that uses `@shardlens/http` instead passes. A warning when neither is found. | | Collector URL | The URL is HTTPS, or plain HTTP to `localhost`, `127.0.0.1` or `[::1]` for development, as the SDK requires. It must not contain a user name or password. | | Collector reachable | `/healthz` answers like a Shardlens collector within 5 seconds. A redirect fails this check: use the address it redirects to. | | Ingest key | `/v1/config` accepts the key, and for which application. It tells a read key or a mistyped key from one the collector doesn’t know. | | Data mode | Privacy or audit mode, and how often salts rotate. | | Salt available | The collector served a salt, which the SDK needs to hash user IDs. | `doctor` stops at the first collector check that fails, so a stopped collector isn’t reported as a rejected key. It connects only to the collector URL, sends nothing to a plain-HTTP address that isn’t on this machine (that would send the key unencrypted), and doesn’t follow redirects. When a request fails, it says why in words, followed by Node’s error code, such as `no DNS record for stats.example.com (ENOTFOUND)`. It exits with code 1 when a check fails, so you can use it in a deploy script. ### A certificate from a private CA [Section titled “A certificate from a private CA”](#a-certificate-from-a-private-ca) For names that end in `.localhost`, `.local`, `.internal` or `.home.arpa`, Caddy signs the certificate with its own certificate authority instead of getting one from a public one, and `doctor` reports that the certificate isn’t trusted. Copy Caddy’s root certificate out of the container and point `NODE_EXTRA_CA_CERTS` at it, for `doctor` and for the bot: ```sh docker compose cp caddy:/data/caddy/pki/authorities/local/root.crt caddy-root.crt NODE_EXTRA_CA_CERTS=./caddy-root.crt npx shardlens doctor ``` # Collector environment > Every environment variable the collector reads. The collector reads its configuration from environment variables (with Docker Compose, from `.env`). It refuses to start when a required variable is missing or invalid, and the error names the variable without printing its value. Empty values count as unset. ## Required [Section titled “Required”](#required) | Variable | What it is | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `DATABASE_URL` | PostgreSQL 16 or newer, for example `postgres://user:password@host:5432/shardlens`. Add `?sslmode=require` for a managed database. Docker Compose builds it from `POSTGRES_PASSWORD`. | | `SHARDLENS_PUBLIC_URL` | The URL people and bots use, for example `https://stats.example.com`. Used for sign-in redirects and links in alerts. | | `SHARDLENS_APP_ID` | Your Discord application ID. The collector serves one application. | | `SHARDLENS_SESSION_SECRET` | At least 32 characters. Signs the short-lived cookies of Discord sign-in (dashboard sessions themselves are random IDs stored hashed). `openssl rand -base64 32` | | `SHARDLENS_SETTINGS_KEY` | 32 random bytes, base64. Encrypts stored secrets such as alert webhook URLs. `openssl rand -base64 32` | ## Keys [Section titled “Keys”](#keys) | Variable | What it is | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SHARDLENS_INGEST_KEY` | An ingest key (`slk_ingest_` and 43 characters) for your bot. Registered when the collector starts. | | `SHARDLENS_READ_KEY` | A read key (`slk_read_` and 43 characters) for read-only dashboard access, scripts and [a dashboard of your own](../../guides/your-own-dashboard/). | | `SHARDLENS_ACTIVITY_KEY` | Optional. An activity key (`slk_activity_` and 43 characters): reads everything a read key does, and [who ran what](../../guides/audit-mode/#read-it-from-your-own-dashboard) while the collector is in audit mode. For the server side of your own dashboard only. | Set both on a first install ([`npx shardlens init`](../cli/#init) does). Each is registered when the collector starts; a new value revokes the key the variable held before, so replacing one in `.env` and restarting is how a leaked key is replaced, with or without the dashboard. A replaced key can’t be brought back: generate a new one. Several collector instances on one database need the same values, or each revokes the others’ keys as it starts. Keys made in Settings can’t take one of these variable names as their label. More keys can be created and revoked in the dashboard (**Settings → API keys**), but Settings needs Discord sign-in, and Discord sign-in only knows your owner and team once the bot has reported them, so a collector with neither key and no `SHARDLENS_EXTRA_ADMINS` can’t be opened. The collector logs a warning at start-up when the bot or you would have no way in. Generate keys with [`npx shardlens keys`](../cli/#keys). ## Discord [Section titled “Discord”](#discord) | Variable | What it is | | ------------------------ | ------------------------------------------------------------------------------------------------------------ | | `DISCORD_CLIENT_ID` | OAuth2 client ID, for “Sign in with Discord”. Set it together with `DISCORD_CLIENT_SECRET`. | | `DISCORD_CLIENT_SECRET` | OAuth2 client secret. | | `DISCORD_PUBLIC_KEY` | The application’s public key (64 hex characters), to receive [webhook events](../../guides/webhook-events/). | | `SHARDLENS_EXTRA_ADMINS` | Comma-separated Discord user IDs allowed full dashboard access besides the application owner and team. | ## Audit mode [Section titled “Audit mode”](#audit-mode) | Variable | What it is | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SHARDLENS_AUDIT_KEY` | 32 random bytes, base64. Encrypts audit-mode identities. Without it, audit mode can’t be turned on. | | `SHARDLENS_MODE` | Optional. `privacy` or `audit`: decides hashed or identified users here instead of in **Settings → User identity**, which then shows the choice but can’t change it. The way to choose audit mode when the dashboard is off. `audit` needs `SHARDLENS_AUDIT_KEY`. Give every collector instance the same value: each one sets it as it starts. | Caution Keep `SHARDLENS_SETTINGS_KEY` and `SHARDLENS_AUDIT_KEY` somewhere safe outside the server. Data encrypted with them can’t be read without them, including from backups. ## Server [Section titled “Server”](#server) | Variable | Default | What it is | | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `PORT` | `8080` | Port to listen on. Docker Compose, Railway and Render set it for you. | | `HOST` | `0.0.0.0` | Address to listen on. Docker Compose sets it. | | `SHARDLENS_TRUST_PROXY` | `false` | Behind a reverse proxy or load balancer, the number of proxies in front (`1` for one), so client addresses and HTTPS are seen correctly. Docker Compose uses `1` (Caddy) unless `.env` sets another number. `true` trusts the whole `X-Forwarded-For` header, which is only safe behind a proxy that replaces it rather than adding to it. | | `SHARDLENS_DEMO` | `false` | `true` lets anyone view the dashboard without signing in, read-only. For a public demo with seeded data only; never with real data. Settings, keys, alerts, audit data and ingest stay locked. | | `SHARDLENS_DASHBOARD` | `on` | `off` stops serving the dashboard pages: the collector is an API only, for [a dashboard of your own or none](../../getting-started/choose-your-setup/). Ingest, queries, jobs, reports and alerts carry on; their Discord messages no longer link to a dashboard. | | `SHARDLENS_DASHBOARD_DIR` | (bundled) | Serve the dashboard from another folder. Mainly for development; restart the collector after rebuilding the dashboard, because it lists the files when it starts. | | `LOG_LEVEL` | `info` | `fatal`, `error`, `warn`, `info`, `debug`, `trace` or `silent`. Per-request logs, which contain URLs, are written at `debug` and `trace` only. | ## ClickHouse (preview) [Section titled “ClickHouse (preview)”](#clickhouse-preview) | Variable | What it is | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CLICKHOUSE_URL` | Optional. `http://user:password@host:8123/database` of a ClickHouse server to use as an [analytics store](../../self-hosting/scaling/#clickhouse-preview). The database is created if missing. `docker-compose.clickhouse.yml` sets it. Never logged. | ## Your own database [Section titled “Your own database”](#your-own-database) | Variable | Default | What it is | | ------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SHARDLENS_SINK_URL` | off | Optional. A `mongodb://`, `mongodb+srv://`, `mysql://`, `mariadb://`, `postgres://` or `sqlite:` URL to [copy every event into](../../self-hosting/your-own-database/). Never logged. | | `SHARDLENS_SINK_TABLE` | `shardlens_events` | Table or collection the copies go to. Letters, digits and underscores, up to 48 characters. | | `SHARDLENS_SINK_RETENTION_DAYS` | `35` | Days copies are kept, 1 to 3,650. | | `SHARDLENS_SINK_EVENTS` | every type | Comma-separated event types to copy, for example `interaction,message_command,custom`. | ## Docker Compose only [Section titled “Docker Compose only”](#docker-compose-only) These are read by `docker-compose.yml`, not by the collector itself. | Variable | What it is | | --------------------- | ---------------------------------------------------------------------------------------------------- | | `SHARDLENS_DOMAIN` | The domain Caddy gets a certificate for. | | `POSTGRES_PASSWORD` | Password for the bundled PostgreSQL. Letters, digits, `-` and `_` only: it goes into `DATABASE_URL`. | | `SHARDLENS_IMAGE` | Collector image to run. Empty or unset, the published image for the current major version. | | `CLICKHOUSE_PASSWORD` | Password for the bundled ClickHouse in `docker-compose.clickhouse.yml`. Letters and digits only. | # Docker Compose > The standard deployment — Caddy for HTTPS, the collector with the dashboard, and PostgreSQL. The standard deployment runs three containers on one server: * **Caddy** terminates HTTPS with an automatic certificate and forwards to the collector. * **The collector** receives events, runs the background jobs and serves the dashboard and API. * **PostgreSQL 17** stores everything. It is never published to the host. A small VPS (1 vCPU, 1 GB RAM) is enough for most bots. ## Install [Section titled “Install”](#install) 1. **Point a domain at your server** Create an `A` (and `AAAA`) record such as `stats.example.com`. Ports 80 and 443 must be reachable for the certificate. 2. **Generate the files** ```sh npx shardlens init --domain stats.example.com --app-id ``` * shardlens/ * docker-compose.yml * Caddyfile * .env secrets and keys, generated; never commit it * bot.env the bot’s two settings, to copy to where the bot runs `init` refuses to overwrite any of these files unless you pass `--force`, which replaces the others and updates an existing `.env` in place, keeping its secrets. You can also copy `deploy/` from the repository and fill in `.env.example` yourself; every variable is described in the [environment reference](../../reference/environment/). 3. **Start it** ```sh cd shardlens && docker compose up -d docker compose logs -f collector ``` The collector applies its database migrations, then starts listening. Open `https://stats.example.com`. 4. **Check it** ```sh docker compose ps # collector "healthy" after up to a minute curl https://stats.example.com/readyz # {"ok":true} once the database is migrated ``` Then start your bot with the two settings from `bot.env`. The live tiles on the Overview count its first events within seconds; the chart and checklist follow within a minute or two, without reloading. Behind another proxy or a CDN in front of Caddy (Cloudflare, say), set `SHARDLENS_TRUST_PROXY=2` in `.env`, so rate limits see each visitor’s own address. Caddy alone counts as one, which is the default. ## Discord sign-in [Section titled “Discord sign-in”](#discord-sign-in) The dashboard accepts two kinds of sign-in: * **Read key**: anyone with `SHARDLENS_READ_KEY` can view the dashboard. Settings, keys, alerts and audit pages stay locked. * **Sign in with Discord**: the application’s owner and team members (and any IDs in `SHARDLENS_EXTRA_ADMINS`) get full access. To turn on Discord sign-in: 1. In the [Developer Portal](https://discord.com/developers/applications), open your application → **OAuth2**. 2. Add the redirect `https://stats.example.com/auth/discord/callback`. 3. Copy the client ID and secret into `.env` as `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET`. 4. `docker compose up -d` to restart the collector. ## Hardening that is already done [Section titled “Hardening that is already done”](#hardening-that-is-already-done) * The collector container runs as a non-root user that can’t change the collector’s own files, with a read-only root filesystem, no Linux capabilities and `no-new-privileges`. * PostgreSQL has no published port; only the collector can reach it. * The dashboard is served with a strict Content Security Policy. * API keys are stored as SHA-256 hashes, and the settings that hold secrets (alert webhooks) are encrypted with `SHARDLENS_SETTINGS_KEY`. ## Updating [Section titled “Updating”](#updating) `docker compose pull && docker compose up -d`. Read [Upgrading](../upgrading/) first: it says what to back up and what changes between versions. ## Backups [Section titled “Backups”](#backups) Back up the database with `pg_dump`. See [Backups](../../operations/backups/). Caution Keep a copy of `.env` somewhere safe. Without `SHARDLENS_SETTINGS_KEY` the encrypted settings in a backup can’t be read, and without `SHARDLENS_AUDIT_KEY` neither can audit-mode data. # Embedded mode > The collector and dashboard inside your bot process, with no separate database server. Embedded mode is for small bots on one host that don’t want to run anything else. The collector, its background jobs and the dashboard run inside your bot process, on an in-process PostgreSQL ([PGlite](https://pglite.dev)) stored in one folder. It is the same code as the standalone collector, so the dashboard, privacy model and features are the same. If your bot already has a database (MongoDB, MySQL, MariaDB, PostgreSQL or SQLite), embedded mode can also [copy every event into it](../your-own-database/). * pnpm `pnpm add @shardlens/discordjs @shardlens/collector @electric-sql/pglite` * npm `npm install @shardlens/discordjs @shardlens/collector @electric-sql/pglite` bot.ts ```ts import { startEmbeddedCollector } from '@shardlens/collector/embedded'; import { createShardlens } from '@shardlens/discordjs'; import { Client, GatewayIntentBits } from 'discord.js'; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // The collector, its jobs and the dashboard, inside this process. Data lives in ./shardlens-data. const collector = await startEmbeddedCollector({ dataDir: './shardlens-data', appId: process.env.DISCORD_APP_ID!, port: 8080, // dashboard on http://127.0.0.1:8080 }); const lens = createShardlens(client, { endpoint: collector.url, apiKey: collector.ingestKey }); console.log(`Shardlens: ${collector.dashboardUrl} (read key in ./shardlens-data/secrets.json)`); await client.login(process.env.DISCORD_TOKEN); for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await lens.shutdown(); // send what is queued while the collector is still there await client.destroy(); await collector.close(); process.exit(0); }); } ``` Open `http://127.0.0.1:8080` and sign in with the read key from `secrets.json`, or set up [Discord sign-in](../docker-compose/#discord-sign-in) by passing `discord: { clientId, clientSecret }` and `publicUrl`. Three things to know before you paste it: * **Node.js 24.11 or newer.** That is the collector’s requirement; the SDK on its own runs on 22.12. * **It uses top-level `await`**, which needs an ES module (`"type": "module"`, or a `.mjs` file). In CommonJS, put the same lines inside the `async` function that starts your bot, and keep `lens` on the client (`client.lens = lens`) so listeners registered earlier can reach it. * **Starting can fail.** The SDK never throws into your bot, but `startEmbeddedCollector` does when it can’t do its job: `appId` isn’t an application ID, the port is already in use, or the data folder can’t be written. Above, that stops the bot. To start without analytics instead, add `.catch()` to the call and pass the (then missing) `url` and `ingestKey` on: without them the SDK records nothing and says so once. On shutdown, call `lens.shutdown()` first, so queued events reach the collector, and `collector.close()` last. ## What’s in the data folder [Section titled “What’s in the data folder”](#whats-in-the-data-folder) * shardlens-data/ * db/ the database (PGlite) * … * secrets.json session secret, settings key, ingest, read and activity keys; generated on first start Back the folder up while the bot is stopped, and keep it private: `secrets.json` holds your keys. To replace a key that leaked, delete its line from `secrets.json` and restart the bot: a new one is generated, and the old one stops working. On Linux and macOS the folder and the file are created readable by your bot’s user only. Windows has no such file mode, so there the folder inherits the permissions of the folder it is in: put it somewhere other users can’t read. ## Options [Section titled “Options”](#options) | Option | Default | What it does | | ------------------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataDir` | (required) | Where the database and secrets live. | | `appId` | (required) | Your Discord application ID. | | `dashboard` | `true` | `false` serves the API only: for [a dashboard of your own or none](../../getting-started/choose-your-setup/), read with `@shardlens/client` and `collector.readKey`. | | `mode` | chosen in Settings | `'privacy'` or `'audit'`, decided here instead of in the dashboard’s Settings. The way to choose [audit mode](../../guides/audit-mode/) with `dashboard: false`; `'audit'` needs `auditKey`. | | `port` | `8080` | Dashboard and API port. | | `host` | `127.0.0.1` | Address to listen on. The default keeps the dashboard private to this machine. | | `publicUrl` | `http://localhost:` | The URL people open the dashboard at (sign-in redirects, alert links). | | `discord` | none | `{ clientId, clientSecret }` for “Sign in with Discord”. | | `discordPublicKey` | none | Receive [webhook events](../../guides/webhook-events/); needs a public HTTPS URL. | | `auditKey` | none | Allows [audit mode](../../guides/audit-mode/). Keep it outside `dataDir`. | | `extraAdmins` | none | Discord user IDs allowed into the dashboard besides the app owner and team. | | `trustProxy` | `false` | Behind a reverse proxy, the number of proxies in front (`1` for one), so rate limits see each visitor’s address. | | `sink` | none | Also copy every event into [your own database](../your-own-database/). | | `logLevel` | `warn` | Collector log level, kept quiet so your bot’s logs stay readable. | `startEmbeddedCollector` resolves to the collector’s `url` and `ingestKey` (for the SDK), `dashboardUrl`, `readKey` and `activityKey` (for the dashboard, and for `@shardlens/client`), and `close()`. ## When to use the standalone collector instead [Section titled “When to use the standalone collector instead”](#when-to-use-the-standalone-collector-instead) * **Bigger bots.** Embedded mode shares your bot’s CPU, and the database has one connection. Beyond a few hundred servers, or if the dashboard feels slow, use [Docker Compose](../docker-compose/). * **Small machines.** PGlite runs PostgreSQL in WebAssembly inside your process: a small bot with an embedded collector used 350 to 550 MB of memory in our tests. * **Several processes.** With `ShardingManager` or clusters, run one standalone collector and point every process at it. An embedded collector belongs to one process. * **Public dashboards and webhook events** need HTTPS in front, which a reverse proxy gives you more easily with the standalone setup. Note Embedded mode uses PGlite rather than SQLite so it runs exactly the same SQL as the standalone collector. The reasoning is in [ADR 0012](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0012-embedded-mode-on-pglite.md). Moving an embedded database to a standalone PostgreSQL isn’t automated yet. # Exporter only > Bot-health metrics in Prometheus or OpenTelemetry, with or without a collector. If you already run Prometheus or an OpenTelemetry pipeline, Shardlens can send its bot-health metrics there. You can use an exporter **instead of** a collector (leave out `endpoint` and `apiKey`) or **as well as** one. * Prometheus * pnpm `pnpm add @shardlens/discordjs @shardlens/exporter-prometheus prom-client` * npm `npm install @shardlens/discordjs @shardlens/exporter-prometheus prom-client` bot.ts ```ts import { createShardlens } from '@shardlens/discordjs'; import { prometheusExporter } from '@shardlens/exporter-prometheus'; import { Client, GatewayIntentBits } from 'discord.js'; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); const prometheus = prometheusExporter(); createShardlens(client, { exporters: [prometheus] }); // no endpoint or apiKey: exporter only // GET http://127.0.0.1:9464/metrics. Under a ShardingManager, shard 1's process serves on 9465, and so on. await prometheus.serve({ port: 9464 + (client.shard?.ids[0] ?? 0) }); await client.login(process.env.DISCORD_TOKEN); ``` Then add the bot as a scrape target: prometheus.yml ```yaml scrape_configs: - job_name: discord-bot static_configs: - targets: ['127.0.0.1:9464'] ``` * `serve()` listens on `127.0.0.1`. When Prometheus runs in another container or on another machine, pass `host: '0.0.0.0'` and keep the port off the public internet (a firewall, or a private Docker network). * `serve()` never throws into your bot. If the port is taken, it logs a warning and tries again every 10 seconds, so a restart that overlaps with the old process still ends up serving. * Each process has its own metrics. With discord.js’s `ShardingManager` the snippet gives each shard process its own port (9464, 9465…); with discord-hybrid-sharding use `9464 + ClusterClient.getInfo().CLUSTER`. Scrape every port: the dashboard adds them up. If your bot already serves `/metrics`, register Shardlens’s metrics on your own registry instead: metrics.ts ```ts import { prometheusExporter } from '@shardlens/exporter-prometheus'; import { collectDefaultMetrics, Registry } from 'prom-client'; // Already serving your own /metrics? Put Shardlens's metrics on your registry instead of starting a server. export const registry = new Registry(); collectDefaultMetrics({ register: registry }); export const prometheus = prometheusExporter({ registry }); ``` prom-client or @prometheus-io/client `prom-client` is deprecated in favour of `@prometheus-io/client`, its successor from the Prometheus project. The exporter works with `prom-client` 15 and `@prometheus-io/client` 0.16. To use the new one, install it under the name the exporter imports: `npm install prom-client@npm:@prometheus-io/client`. * OpenTelemetry `pnpm add @shardlens/discordjs @shardlens/exporter-prometheus prom-client` * pnpm `npm install @shardlens/discordjs @shardlens/exporter-prometheus prom-client` * npm * pnpm `pnpm add @shardlens/discordjs @shardlens/exporter-otel @opentelemetry/api` * npm `npm install @shardlens/discordjs @shardlens/exporter-otel @opentelemetry/api` bot.ts ```ts import { createShardlens } from '@shardlens/discordjs'; import { openTelemetryExporter } from '@shardlens/exporter-otel'; import { Client, GatewayIntentBits } from 'discord.js'; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // Records through the global MeterProvider your OpenTelemetry SDK registers (OTLP, Prometheus, a vendor…). createShardlens(client, { endpoint: process.env.SHARDLENS_URL, // optional: keep sending to a collector too apiKey: process.env.SHARDLENS_INGEST_KEY, exporters: [openTelemetryExporter()], }); await client.login(process.env.DISCORD_TOKEN); ``` The exporter only uses the OpenTelemetry API. It records through the global `MeterProvider` (also one your SDK registers after the exporter was created), or through the `meter` you pass. If you don’t have an SDK set up yet, this sends the metrics over OTLP to the address in `OTEL_EXPORTER_OTLP_ENDPOINT` (default `http://localhost:4318`): ```sh npm install @opentelemetry/sdk-metrics @opentelemetry/exporter-metrics-otlp-http ``` telemetry.ts ```ts import { metrics } from '@opentelemetry/api'; import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'; import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'; const reader = new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter(), exportIntervalMillis: 15_000 }); metrics.setGlobalMeterProvider(new MeterProvider({ readers: [reader] })); ``` An OpenTelemetry Collector that receives it and exposes it to Prometheus: otel-collector.yaml ```yaml receivers: otlp: protocols: http: endpoint: 0.0.0.0:4318 exporters: prometheus: endpoint: 0.0.0.0:8889 service: pipelines: metrics: receivers: [otlp] exporters: [prometheus] ``` Prometheus then scrapes the collector on port 8889. Prometheus 3 can also receive OTLP itself: start it with `--web.enable-otlp-receiver` and set `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` to `http://prometheus:9090/api/v1/otlp/v1/metrics`; the `job` label is then your service name. Either way the names are the ones in the table below, so the [Grafana dashboard](../../guides/grafana/) works with either exporter. * pnpm `pnpm add @shardlens/discordjs @shardlens/exporter-otel @opentelemetry/api` * npm `npm install @shardlens/discordjs @shardlens/exporter-otel @opentelemetry/api` ## What is exported [Section titled “What is exported”](#what-is-exported) Both exporters register the same instruments, from one shared definition in `@shardlens/core`. OpenTelemetry instruments have UCUM units (`s`, `By`, and `{interaction}`, `{server}` and so on for counts), which Prometheus translators turn into the Prometheus names. | Prometheus | OpenTelemetry | Type | Labels | Description | | ---------------------------------------- | --------------------------------- | --------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `shardlens_interactions_total` | `shardlens.interactions` | counter | `kind`, `command`, `outcome` | Interactions handled (commands, context menus, components, modals, autocomplete) and message (prefix) commands, by outcome. | | `shardlens_interaction_response_seconds` | `shardlens.interaction_response` | histogram | `kind`, `command` | Time from Discord's interaction timestamp to the first response. Discord's deadline is 3 seconds. | | `shardlens_interaction_handler_seconds` | `shardlens.interaction_handler` | histogram | `kind`, `command` | Time spent in a handler wrapped with lens.wrap(), or reported for a message command. | | `shardlens_interaction_errors_total` | `shardlens.interaction_errors` | counter | `command`, `error_class` | Errors thrown by wrapped handlers, by error class (never the message). | | `shardlens_rest_requests_total` | `shardlens.rest_requests` | counter | `method`, `route`, `status` | REST requests to Discord, by method, bucketed route and status. | | `shardlens_rest_invalid_requests_total` | `shardlens.rest_invalid_requests` | counter | `status` | Responses that count towards Discord's invalid-request limit (10,000 per 10 minutes per IP). | | `shardlens_ratelimits_total` | `shardlens.ratelimits` | counter | `scope` | Requests held back for a rate limit, by scope (user, global or shared). | | `shardlens_shard_events_total` | `shardlens.shard_events` | counter | `shard`, `state` | Shard state changes (ready, resumed, reconnecting, disconnected, error, invalidated). | | `shardlens_guild_events_total` | `shardlens.guild_events` | counter | `event` | Servers joined and left, and outages (unavailable, available). | | `shardlens_custom_events_total` | `shardlens.custom_events` | counter | `name` | Custom events recorded with track(), by name. | | `shardlens_entitlements_total` | `shardlens.entitlements` | counter | `action` | Entitlement changes (create, update, delete). | | `shardlens_shard_ping_seconds` | `shardlens.shard_ping` | gauge | `shard` | Gateway heartbeat latency per shard. | | `shardlens_guilds` | `shardlens.guilds` | gauge | `shard` | Servers per shard. | | `shardlens_eventloop_delay_p99_seconds` | `shardlens.eventloop_delay_p99` | gauge | — | Event loop delay, 99th percentile over the last 30 seconds. | | `shardlens_memory_bytes` | `shardlens.memory` | gauge | `type` | Process memory (rss, heap_used). | | `shardlens_cache_size` | `shardlens.cache_size` | gauge | `cache` | discord.js cache sizes (users, channels). | | `shardlens_identify_remaining` | `shardlens.identify_remaining` | gauge | — | Gateway sessions left in Discord's daily identify budget. | Gauges appear once they have a value: process gauges after 30 seconds, ping once a shard has had a heartbeat, the identify budget on the process that runs shard 0. ## Privacy and cardinality [Section titled “Privacy and cardinality”](#privacy-and-cardinality) * **No user or server labels.** Exporters see events before hashing, with user fields blanked and audit-mode identities removed, and no metric is labelled by user or server ID. That keeps your metrics anonymous and their cardinality bounded. * Labels are command names, bucketed REST routes (`/channels/:id/messages`), statuses, shard numbers and the custom event names you chose. Custom IDs of buttons, menus and modals are never a label: components count under the command that sent their message. * A label that would take more than 1,000 values in one metric, such as custom event names built from IDs, counts the rest as `(other)` in the Prometheus exporter. OpenTelemetry SDKs have their own limit (2,000 attribute sets per metric by default). * Counts are exact: exporters see every event before any `sampleRate` sampling. ## What you don’t get without a collector [Section titled “What you don’t get without a collector”](#what-you-dont-get-without-a-collector) Exporters cover bot health. Product analytics (unique users, retention, servers, growth, audience) need the collector, because they depend on salted user hashes and long-term storage. Tip Import the ready-made [Grafana dashboard](../../guides/grafana/) to get started. # Railway > Run the collector on Railway with a managed PostgreSQL database. Railway builds the collector from the repository using `deploy/railway.json` and gives you HTTPS on a `*.up.railway.app` domain or your own. 1. **Create a project from the repository** In Railway, choose **New project → Deploy from GitHub repo** and pick your fork of Shardlens. In the service’s **Settings → Config-as-code**, set the config file to `/deploy/railway.json`. Railway then builds `apps/collector/Dockerfile` and checks `/readyz` before switching traffic. 2. **Add PostgreSQL** **New → Database → PostgreSQL** in the same project. 3. **Generate a domain** under the service’s **Settings → Networking**. The collector needs its own address in the next step. 4. **Set the variables** on the collector service | Variable | Value | | -------------------------- | ------------------------------------ | | `DATABASE_URL` | `${{Postgres.DATABASE_URL}}` | | `SHARDLENS_PUBLIC_URL` | `https://${{RAILWAY_PUBLIC_DOMAIN}}` | | `SHARDLENS_APP_ID` | Your Discord application ID | | `SHARDLENS_SESSION_SECRET` | `openssl rand -base64 32` | | `SHARDLENS_SETTINGS_KEY` | `openssl rand -base64 32` | | `SHARDLENS_INGEST_KEY` | `npx shardlens keys --scope ingest` | | `SHARDLENS_READ_KEY` | `npx shardlens keys --scope read` | | `SHARDLENS_TRUST_PROXY` | `1` | `${{RAILWAY_PUBLIC_DOMAIN}}` is the `*.up.railway.app` domain from step 3. With your own domain, write its URL instead. Railway sets `PORT`, and the collector listens on it. The optional variables are in the [environment reference](../../reference/environment/). 5. **Deploy**, then open the domain. Tip Point your bot’s `SHARDLENS_URL` at the Railway URL and use the ingest key you set above. # Render > Deploy the collector and PostgreSQL on Render with the Blueprint in the repository. The repository has a Render Blueprint (`deploy/render.yaml`) that creates the collector as a Docker web service and a Render PostgreSQL 17 database, wires `DATABASE_URL`, and generates the session secret and settings key. 1. **Create the Blueprint** In Render, choose **New → Blueprint**, connect your fork of Shardlens and set **Blueprint path** to `deploy/render.yaml`. Render shows the `shardlens` service and the `shardlens-db` database. 2. **Fill in the variables Render asks for** | Variable | Value | | ---------------------- | -------------------------------------------------------------- | | `SHARDLENS_PUBLIC_URL` | Your service URL, for example `https://shardlens.onrender.com` | | `SHARDLENS_APP_ID` | Your Discord application ID | | `SHARDLENS_INGEST_KEY` | `npx shardlens keys --scope ingest` | | `SHARDLENS_READ_KEY` | `npx shardlens keys --scope read` | The service URL is `https://` followed by the service name and `.onrender.com`, but Render adds a few characters when that name is taken. After the first deploy, compare it with the URL at the top of the service’s page and, if they differ, correct `SHARDLENS_PUBLIC_URL` under **Environment**: Discord sign-in and the links in alerts and reports use it. Leave `DISCORD_CLIENT_ID`, `DISCORD_CLIENT_SECRET` and `DISCORD_PUBLIC_KEY` empty unless you want Discord sign-in or [webhook events](../../guides/webhook-events/). `SHARDLENS_SESSION_SECRET` and `SHARDLENS_SETTINGS_KEY` are generated for you; copy the settings key somewhere safe, because encrypted settings can’t be read without it. 3. **Apply**. Render builds the image, the collector applies its migrations, and the health check on `/readyz` turns green. Caution Free Render services sleep when idle, and the SDK then buffers events until the collector wakes. Use a paid instance for a bot in production. # Scaling > Running several collectors, and when to think about ClickHouse. One collector on 1 vCPU handles a large bot. When you need more, the collector scales horizontally. ## How much one collector handles [Section titled “How much one collector handles”](#how-much-one-collector-handles) Measured with the k6 script in `tests/load/ingest.js` against the collector image limited to one CPU (`--cpus=1`), with PostgreSQL 17 alongside, sending gzipped batches of 500 realistic events (hashed users, commands, custom events): | Rate | Accepted | Latency per batch (p50 / p95 / p99) | | -------------- | -------- | ----------------------------------- | | 5,000 events/s | 100% | 66 / 75 / 87 ms | | 8,000 events/s | 100% | 72 / 84 / 102 ms | The spec’s target is 5,000 events/s per instance on 1 vCPU. The `load` workflow repeats the measurement weekly. For reference, a bot running 100 commands a second sends far less than 1,000 events a second. ## Several collectors [Section titled “Several collectors”](#several-collectors) Ingest is stateless, so you can run several collectors behind a load balancer against the same PostgreSQL database: * **Migrations** run under an advisory lock, so collectors can start at the same time. * **Background jobs** (rollups, unique users, salts, partitions and retention, alerts and reports) run on one collector at a time. They take a PostgreSQL advisory lock (`pg_try_advisory_lock`), and another collector takes over within 30 seconds if the leader stops. * **Live tiles** are shared through `LISTEN/NOTIFY`, so every collector’s dashboard sees every event. * **Back-pressure**: when a collector is busy it answers `503` with `Retry-After`, and the SDK keeps the batch and retries with jitter. * **Keys** are checked against the database and remembered for a minute, so a key revoked on one collector stops working on the others within a minute. Sessions and settings are read from the database on every request. * **Upgrades** can be rolling, except from 1.0 on a PostgreSQL that isn’t set to UTC (see [Upgrading](../upgrading/#from-10-to-11)). Set `SHARDLENS_TRUST_PROXY` to the number of proxies in front (`1` for one load balancer), so rate limits see client addresses. ## PostgreSQL [Section titled “PostgreSQL”](#postgresql) Raw events are stored in daily partitions and dropped whole when they expire, so deletes are cheap. Charts read from minute, hour and day rollups, never from raw rows, so dashboards stay fast as data grows. * Give PostgreSQL fast storage and enough memory for the current day’s partitions. * Use a managed database with TLS for larger installs (`DATABASE_URL=postgres://…?sslmode=require`). * Lower raw retention (Settings → General, 7 to 90 days) if disk is the constraint. Aggregates are kept regardless: minute rollups for 14 days, hourly ones for 13 months and daily ones for good. * Server history (joins, leaves and outages), shard state changes, entitlements, subscriptions and command permission changes are small and kept with no automatic expiry. ## ClickHouse (preview) [Section titled “ClickHouse (preview)”](#clickhouse-preview) For bots with very high event volumes, the collector can also keep interactions and custom events in ClickHouse and answer the heaviest chart queries from there. ```sh echo "CLICKHOUSE_PASSWORD=$(openssl rand -hex 24)" >> .env docker compose -f docker-compose.yml -f docker-compose.clickhouse.yml up -d ``` How it works: * **PostgreSQL stays the system of record.** Everything is still written there; ClickHouse gets a copy of the interactions and custom events PostgreSQL accepted (retries are never counted twice). Copying happens after the write, from a bounded buffer, so a slow or unavailable ClickHouse never slows down or fails ingest. * **Charts** (series, top values and heatmaps of interactions and custom events) are answered from ClickHouse’s minute rollups for any range that starts after ClickHouse was enabled. Older ranges, and every other page, use PostgreSQL. * **Storage**: raw rows are `MergeTree` tables kept for 35 days, whatever the raw retention in Settings; minute rollups are `AggregatingMergeTree` tables (`sumState`, `quantilesTDigest` and `uniqState` of the salted user hash) kept for 400 days. With a raw retention shorter than 35 days, ClickHouse keeps hashed rows longer than PostgreSQL does: say so in your privacy policy, or shorten the table TTL yourself (`ALTER TABLE interactions MODIFY TTL toDateTime(ts) + INTERVAL 7 DAY`, and the same for `custom_events`). * **Privacy**: ClickHouse only ever sees salted hashes, never user IDs, and an erasure request deletes the same rows there as in PostgreSQL. Caution This is a preview: the data model may change before it is marked stable, in which case the ClickHouse database can be dropped and refilled from new events. Set it with `CLICKHOUSE_URL` ([environment reference](../../reference/environment/)). ## Very large bots [Section titled “Very large bots”](#very-large-bots) If your bot handles millions of interactions a day, sample high-volume event types in the SDK with `sampleRate`. Sampled events carry their weight, so totals stay correct. # Upgrading > How versions, migrations and the wire format change between releases. ## Upgrading the collector [Section titled “Upgrading the collector”](#upgrading-the-collector) 1. Back up the database ([Backups](../../operations/backups/)). 2. Read the release notes for anything marked as breaking. 3. Pull the new image and restart: ```sh docker compose pull && docker compose up -d ``` Building from a checkout of the repository instead: `git pull && docker compose up -d --build`. 4. Watch it start: `docker compose logs -f collector` lists the migrations it applied (`migrationsApplied`) in the `Shardlens collector started` line. The collector applies database migrations when it starts, under an advisory lock, so several collectors can be upgraded at once. Migrations only move forward, and a collector refuses to start against a database migrated by a newer one. To roll back, restore the backup you took and run the previous image with the settings it understands: a 1.0 collector refuses `SHARDLENS_TRUST_PROXY` set to a number of proxies (`1`, which the Compose and Render templates use from 1.1), so set it back to `true` there. ## From 1.0 to 1.1 [Section titled “From 1.0 to 1.1”](#from-10-to-11) * **Dashboard sessions opened with a read key end**, because a session now remembers its key (revoking the key ends them). Sign in with the read key again. Discord sign-ins are kept. * **Rollups move to UTC on a PostgreSQL that isn’t set to UTC.** 1.0 cut hourly and daily rollups in the database server’s time zone (`SHOW timezone;` in `psql`); 1.1 always cuts them in UTC. The upgrade converts what is there: hours and days from the last 13 days are rebuilt exactly from minute rollups, older hours and days move to the UTC hour or day that holds most of them. On a UTC server, which is what the Compose file runs, there is nothing to do. With several collectors, stop every 1.0 collector before the first 1.1 one starts: a 1.0 job leader still running afterwards writes buckets in the server’s time zone again. * **`SHARDLENS_TRUST_PROXY`** takes the number of proxies in front (`1` for Caddy). The Compose file now reads it from `.env`, defaulting to `1`. ## Upgrading the SDK [Section titled “Upgrading the SDK”](#upgrading-the-sdk) Update `@shardlens/discordjs` like any other dependency. You can upgrade the SDK and the collector in either order within the same major version. ## Version policy [Section titled “Version policy”](#version-policy) * Packages follow [semantic versioning](https://semver.org). Breaking changes only come in major versions, with a migration note. * The **wire format** has its own major version (`v` in every batch). A collector accepts the current and the previous major version, so you never have to upgrade every bot on the same day. * The collector image is tagged by full version (`1.2.3`), minor (`1.2`) and major (`1`). Pin a major version in production. * Each release lists its changes in the package changelogs, generated by Changesets. # Your own database > Copy every event into the MongoDB, MySQL, MariaDB, PostgreSQL or SQLite database your bot already uses. Your bot may already have a database. Point Shardlens at it, and every event the collector accepts is also written there, so you can query your bot’s usage with the tools you already have, join it with your own data, or keep it for longer. The dashboard still runs on the collector’s own store: PostgreSQL with Docker, or the built-in database in [embedded mode](../embedded/), which needs no database server at all. Its rollups, histograms, unique-user counts and funnels are built on PostgreSQL, so your database holds a copy of the events rather than replacing it. ## Turn it on [Section titled “Turn it on”](#turn-it-on) Set `SHARDLENS_SINK_URL` on the collector (in Docker Compose, in `.env`) and restart it: * MongoDB ```sh SHARDLENS_SINK_URL=mongodb+srv://user:password@cluster0.example.mongodb.net/mybot ``` MongoDB 5 or newer, including Atlas. The database is the one in the URL (`mybot` here), or `shardlens` if the URL names none. * MySQL / MariaDB ```sh SHARDLENS_SINK_URL=mysql://user:password@db.example.com:3306/mybot # MariaDB: the same, starting with mariadb:// ``` MySQL 8 or MariaDB 10.5 and newer. The database must exist; the table is created. * PostgreSQL ```sh SHARDLENS_SINK_URL=postgres://user:password@db.example.com:5432/mybot ``` Any PostgreSQL 13 or newer (Supabase, Neon, RDS), separate from the collector’s database. * SQLite ```sh SHARDLENS_SINK_URL=sqlite:/data/shardlens-events.db ``` A file on the collector’s machine, through Node’s built-in SQLite. The file is created. SQLite suits [embedded mode](../embedded/) best: in Docker Compose the collector’s file system is read-only, so mount a volume for the file’s folder first. In embedded mode, pass the same URL (or a sink of your own) to `startEmbeddedCollector`: bot.ts ```ts import { type EventSink, type StoredEvent, startEmbeddedCollector } from '@shardlens/collector/embedded'; // Embedded mode, with every event also copied into the MongoDB the bot already uses. A `mysql://`, `mariadb://`, // `postgres://` or `sqlite:./events.db` URL works the same way. const collector = await startEmbeddedCollector({ dataDir: './shardlens-data', appId: process.env.DISCORD_APP_ID!, sink: { to: process.env.MONGODB_URI!, retentionDays: 90 }, }); // Or send copies anywhere, by writing a sink yourself. Writes must ignore an event ID they already hold. declare const myStore: { upsertMany(rows: StoredEvent[]): Promise; deleteWhere(filter: { appId: string; userHashes: readonly string[] } | { before: Date }): Promise; }; const custom: EventSink = { name: 'my-store', write: (events) => myStore.upsertMany([...events]), erase: (appId, userHashes) => myStore.deleteWhere({ appId, userHashes }), expire: (before) => myStore.deleteWhere({ before }), close: async () => undefined, }; const other = await startEmbeddedCollector({ dataDir: './shardlens-other', appId: process.env.DISCORD_APP_ID!, port: 8081, sink: { to: custom, events: ['interaction', 'message_command', 'custom'] }, }); export { collector, other }; ``` The collector log says `sink` with the database’s name when it starts. If the database is unreachable, the collector starts anyway, logs why once a minute (with any password removed), and keeps trying. | Setting | Default | What it does | | ------------------------------- | ------------------ | -------------------------------------------------------------------------------------- | | `SHARDLENS_SINK_URL` | off | Where to copy events. | | `SHARDLENS_SINK_TABLE` | `shardlens_events` | Table or collection name. | | `SHARDLENS_SINK_RETENTION_DAYS` | `35` | Copies older than this are deleted every six hours (1 to 3,650). | | `SHARDLENS_SINK_EVENTS` | every type | Comma-separated event types to copy, for example `interaction,message_command,custom`. | ## What is stored [Section titled “What is stored”](#what-is-stored) One row (or document) per event, with these columns. In MongoDB the event’s own fields sit at the top level of the document instead of in `data`, and `id` is `_id`. | Column | What it holds | | ------------- | ---------------------------------------------------------------------------------- | | `id` | The event’s UUIDv7. A retried batch is stored once. | | `ts` | When the event happened (UTC). | | `app_id` | Your application ID. | | `env` | The SDK’s `environment`, such as `production`. | | `bot_release` | The SDK’s `release`, if you set it. | | `type` | `interaction`, `message_command`, `custom`, `guild_join`, `rest_window` and so on. | | `guild_id` | The server, when the event has one. | | `user_hash` | The salted user hash (32 hex characters), when the event has a user. | | `salt_period` | The salt period of `user_hash`, such as `2026-11`. | | `data` | The whole event, as listed on [Data collected](../../concepts/data-collected/). | ```sql -- Prefix and slash runs per command this week (MySQL; PostgreSQL uses data->>'command') SELECT type, JSON_UNQUOTE(JSON_EXTRACT(data, '$.command')) AS command, count(*) AS runs FROM shardlens_events WHERE type IN ('interaction', 'message_command') AND ts > NOW() - INTERVAL 7 DAY GROUP BY 1, 2 ORDER BY runs DESC; ``` ```js // The same in MongoDB db.shardlens_events.aggregate([ { $match: { type: { $in: ['interaction', 'message_command'] }, ts: { $gt: new Date(Date.now() - 7 * 864e5) } } }, { $group: { _id: { type: '$type', command: '$command' }, runs: { $sum: 1 } } }, { $sort: { runs: -1 } }, ]); ``` ## Privacy [Section titled “Privacy”](#privacy) The copy follows the same rules as the collector: * Users are the same salted hashes, never user IDs. Nothing the [data register](../../concepts/data-collected/) marks as identifying is copied: in audit mode, who ran a command stays in the collector’s encrypted store, and your app team’s IDs (used for dashboard sign-in) stay in the collector. * Erasure reaches the copy: `forgetUser()`, `/privacy erase` and the dashboard’s erase delete from your database the same rows they delete in the collector (in privacy mode, a person’s rows under the salts the bot still holds: the current and previous period), and the request fails (so it is retried) if your database can’t be reached or hasn’t answered within 20 seconds. * Copies are deleted after `SHARDLENS_SINK_RETENTION_DAYS`. If you keep them longer than about a month, their hashes outlive the salt that made them: they can no longer be tied to anyone, or erased by user. * Message content is never collected, so it is never copied. Your privacy policy should name the database you copy to. `npx shardlens privacy` prints a paragraph to start from. ## Limits [Section titled “Limits”](#limits) * Only events accepted from the moment the sink is turned on are copied. Nothing is backfilled. * Copies wait in memory (up to 20,000 events) while your database is down, and are dropped and counted after that. The collector’s own store is unaffected. * If your database keeps refusing a batch while it is reachable (a column too narrow, a strict-mode error), the rows are tried one by one and only those it refuses are dropped and logged, so one bad row never holds up the rest. A sink you write yourself without `init` counts as unreachable while it refuses every row, so nothing is dropped during an outage. * A query to MySQL, MariaDB or PostgreSQL that gets no answer for 30 seconds (a network partition, say) fails and is retried, so a database that stops answering can’t hold the copies up for ever. MongoDB’s driver notices an unreachable server by itself. * Webhook events from Discord (installs and removals sent to the collector directly) are not copied. Tip A sink is not a backup of the dashboard: back up the collector’s database as described in [Backups](../../operations/backups/). # shardlens-monorepo ## Modules [Section titled “Modules”](#modules) * [@shardlens/client](/Shardlens/reference/sdk/shardlens/client/readme/) * [@shardlens/core](/Shardlens/reference/sdk/shardlens/core/readme/) * [@shardlens/discordjs](/Shardlens/reference/sdk/shardlens/discordjs/readme/) * [@shardlens/exporter-otel](/Shardlens/reference/sdk/shardlens/exporter-otel/readme/) * [@shardlens/exporter-prometheus](/Shardlens/reference/sdk/shardlens/exporter-prometheus/readme/) * [@shardlens/http](/Shardlens/reference/sdk/shardlens/http/readme/) # shardlens-monorepo # SDK reference [Section titled “SDK reference”](#sdk-reference) Generated from the TypeScript source. `@shardlens/discordjs` is the package you install; `@shardlens/core` is the transport client it is built on, and its types appear in the adapter’s API. `@shardlens/client` is separate: it reads a collector from your own dashboard or scripts. # ShardlensClientError Defined in: [packages/client/src/errors.ts:5](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/errors.ts#L5) Every failure of the client: an answer other than 2xx, no answer at all, or options it can’t work with. The message never contains the key. ## Extends [Section titled “Extends”](#extends) * `Error` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new ShardlensClientError**(`message`, `details`): `ShardlensClientError` Defined in: [packages/client/src/errors.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/errors.ts#L19) #### Parameters [Section titled “Parameters”](#parameters) ##### message [Section titled “message”](#message) `string` ##### details [Section titled “details”](#details) ###### cause? [Section titled “cause?”](#cause) `unknown` ###### code [Section titled “code”](#code) `string` ###### requestId? [Section titled “requestId?”](#requestid) `string` ###### retryAfterSeconds? [Section titled “retryAfterSeconds?”](#retryafterseconds) `number` ###### status [Section titled “status”](#status) `number` #### Returns [Section titled “Returns”](#returns) `ShardlensClientError` #### Overrides [Section titled “Overrides”](#overrides) `Error.constructor` ## Properties [Section titled “Properties”](#properties) ### cause? [Section titled “cause?”](#cause-1) > `optional` **cause?**: `unknown` Defined in: node_modules/.pnpm/typescript\@6.0.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24 #### Inherited from [Section titled “Inherited from”](#inherited-from) `Error.cause` *** ### code [Section titled “code”](#code-1) > `readonly` **code**: `string` Defined in: [packages/client/src/errors.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/errors.ts#L13) The collector’s error code (`unauthorized`, `invalid_query`, `activity_key_required`, `audit_mode_off`, `rate_limited`…), or `http_` for an answer without one. Without an answer: `timeout`, `network` or `invalid_options`. `invalid_response` is a 2xx answer that isn’t the collector’s JSON. *** ### message [Section titled “message”](#message-1) > **message**: `string` Defined in: node_modules/.pnpm/typescript\@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075 #### Inherited from [Section titled “Inherited from”](#inherited-from-1) `Error.message` *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: node_modules/.pnpm/typescript\@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074 #### Inherited from [Section titled “Inherited from”](#inherited-from-2) `Error.name` *** ### requestId [Section titled “requestId”](#requestid-1) > `readonly` **requestId**: `string` | `undefined` Defined in: [packages/client/src/errors.ts:17](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/errors.ts#L17) The collector’s ID for a request it failed on (a 500), to find it in the collector’s log. *** ### retryAfterSeconds [Section titled “retryAfterSeconds”](#retryafterseconds-1) > `readonly` **retryAfterSeconds**: `number` | `undefined` Defined in: [packages/client/src/errors.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/errors.ts#L15) How long the collector asks to wait before trying again, from `Retry-After` (a 429, or a busy live stream). *** ### stack? [Section titled “stack?”](#stack) > `optional` **stack?**: `string` Defined in: node_modules/.pnpm/typescript\@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076 #### Inherited from [Section titled “Inherited from”](#inherited-from-3) `Error.stack` *** ### status [Section titled “status”](#status-1) > `readonly` **status**: `number` Defined in: [packages/client/src/errors.ts:7](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/errors.ts#L7) The HTTP status of the collector’s answer. `0` when there was none: a timeout, a network failure, bad options. *** ### stackTraceLimit [Section titled “stackTraceLimit”](#stacktracelimit) > `static` **stackTraceLimit**: `number` Defined in: node_modules/.pnpm/@types+node\@24.19.2/node_modules/@types/node/globals.d.ts:68 The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured *after* the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. #### Inherited from [Section titled “Inherited from”](#inherited-from-4) `Error.stackTraceLimit` ## Methods [Section titled “Methods”](#methods) ### captureStackTrace() [Section titled “captureStackTrace()”](#capturestacktrace) > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Defined in: node_modules/.pnpm/@types+node\@24.19.2/node_modules/@types/node/globals.d.ts:52 Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` #### Parameters [Section titled “Parameters”](#parameters-1) ##### targetObject [Section titled “targetObject”](#targetobject) `object` ##### constructorOpt? [Section titled “constructorOpt?”](#constructoropt) `Function` #### Returns [Section titled “Returns”](#returns-1) `void` #### Inherited from [Section titled “Inherited from”](#inherited-from-5) `Error.captureStackTrace` *** ### prepareStackTrace() [Section titled “prepareStackTrace()”](#preparestacktrace) > `static` **prepareStackTrace**(`err`, `stackTraces`): `any` Defined in: node_modules/.pnpm/@types+node\@24.19.2/node_modules/@types/node/globals.d.ts:56 #### Parameters [Section titled “Parameters”](#parameters-2) ##### err [Section titled “err”](#err) `Error` ##### stackTraces [Section titled “stackTraces”](#stacktraces) `CallSite`\[] #### Returns [Section titled “Returns”](#returns-2) `any` #### See [Section titled “See”](#see) #### Inherited from [Section titled “Inherited from”](#inherited-from-6) `Error.prepareStackTrace` # createShardlensClient > **createShardlensClient**(`options`): [`ShardlensClient`](/Shardlens/reference/sdk/shardlens/client/interfaces/shardlensclient/) Defined in: [packages/client/src/client.ts:128](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L128) A client for one collector. Making one never throws and sends nothing: with an `endpoint` or `apiKey` it can’t use, every call rejects with a [ShardlensClientError](/Shardlens/reference/sdk/shardlens/client/classes/shardlensclienterror/) (`invalid_options`) saying why. ## Parameters [Section titled “Parameters”](#parameters) ### options [Section titled “options”](#options) [`ShardlensClientOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/shardlensclientoptions/) ## Returns [Section titled “Returns”](#returns) [`ShardlensClient`](/Shardlens/reference/sdk/shardlens/client/interfaces/shardlensclient/) # lastDays > **lastDays**(`days`): [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/range.ts:5](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/range.ts#L5) The last `days` days up to now, as a query’s `range`. ## Parameters [Section titled “Parameters”](#parameters) ### days [Section titled “days”](#days) `number` ## Returns [Section titled “Returns”](#returns) [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) # ActivityLogFilters Defined in: [packages/client/src/activity.ts:5](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L5) Narrows the activity log. Every filter is optional; together they must all match. ## Properties [Section titled “Properties”](#properties) ### before? [Section titled “before?”](#before) > `optional` **before?**: `string` | `null` Defined in: [packages/client/src/activity.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L11) Paging: the `nextBefore` of the page before (`null` is the same as leaving it out), or a time to start below. *** ### command? [Section titled “command?”](#command) > `optional` **command?**: `string` Defined in: [packages/client/src/activity.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L13) A command’s name, without the slash. *** ### from? [Section titled “from?”](#from) > `optional` **from?**: `string` Defined in: [packages/client/src/activity.ts:7](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L7) Rows at or after this time: an ISO 8601 date-time with an offset. *** ### guild? [Section titled “guild?”](#guild) > `optional` **guild?**: `string` Defined in: [packages/client/src/activity.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L15) A server’s ID. *** ### limit? [Section titled “limit?”](#limit) > `optional` **limit?**: `number` Defined in: [packages/client/src/activity.ts:21](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L21) Rows per page: 1 to 200, default 50. *** ### outcome? [Section titled “outcome?”](#outcome) > `optional` **outcome?**: [`ActivityOutcome`](/Shardlens/reference/sdk/shardlens/client/type-aliases/activityoutcome/) | `"failed"` Defined in: [packages/client/src/activity.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L19) One outcome, or `failed` for every outcome but `ok`. *** ### to? [Section titled “to?”](#to) > `optional` **to?**: `string` Defined in: [packages/client/src/activity.ts:9](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L9) Rows before this time. *** ### user? [Section titled “user?”](#user) > `optional` **user?**: `string` Defined in: [packages/client/src/activity.ts:17](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L17) A user’s Discord ID. The collector records the lookup in its access log. # ActivityLogPage Defined in: [packages/client/src/activity.ts:49](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L49) One page of the activity log, newest first. ## Properties [Section titled “Properties”](#properties) ### nextBefore [Section titled “nextBefore”](#nextbefore) > **nextBefore**: `string` | `null` Defined in: [packages/client/src/activity.ts:55](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L55) Pass as `before` for the next, older page. `null` when this page has fewer rows than `limit`; a full page can be followed by an empty one. *** ### rows [Section titled “rows”](#rows) > **rows**: [`ActivityRow`](/Shardlens/reference/sdk/shardlens/client/interfaces/activityrow/)\[] Defined in: [packages/client/src/activity.ts:50](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L50) # ActivityRow Defined in: [packages/client/src/activity.ts:25](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L25) One interaction in the activity log: who ran what, where, and how it ended. ## Properties [Section titled “Properties”](#properties) ### ackMs [Section titled “ackMs”](#ackms) > **ackMs**: `number` | `null` Defined in: [packages/client/src/activity.ts:39](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L39) Time to the first response, in milliseconds. *** ### avatar [Section titled “avatar”](#avatar) > **avatar**: `string` | `null` Defined in: [packages/client/src/activity.ts:45](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L45) Discord’s avatar hash. *** ### command [Section titled “command”](#command) > **command**: `string` | `null` Defined in: [packages/client/src/activity.ts:34](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L34) *** ### customId [Section titled “customId”](#customid) > **customId**: `string` | `null` Defined in: [packages/client/src/activity.ts:36](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L36) *** ### guildId [Section titled “guildId”](#guildid) > **guildId**: `string` | `null` Defined in: [packages/client/src/activity.ts:29](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L29) *** ### guildName [Section titled “guildName”](#guildname) > **guildName**: `string` | `null` Defined in: [packages/client/src/activity.ts:31](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L31) Text chosen by the server’s owner: render it as text. `null` for a server the collector has no profile of. *** ### interactionId [Section titled “interactionId”](#interactionid) > **interactionId**: `string` Defined in: [packages/client/src/activity.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L27) Shardlens’ own ID of the event (a UUIDv7), not Discord’s interaction ID. Unique, and the order rows are paged in. *** ### kind [Section titled “kind”](#kind) > **kind**: `string` Defined in: [packages/client/src/activity.ts:33](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L33) `chat_input`, `button`, `select`, `modal_submit`, `message_command`… *** ### outcome [Section titled “outcome”](#outcome) > **outcome**: [`ActivityOutcome`](/Shardlens/reference/sdk/shardlens/client/type-aliases/activityoutcome/) Defined in: [packages/client/src/activity.ts:37](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L37) *** ### sub [Section titled “sub”](#sub) > **sub**: `string` | `null` Defined in: [packages/client/src/activity.ts:35](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L35) *** ### ts [Section titled “ts”](#ts) > **ts**: `string` Defined in: [packages/client/src/activity.ts:28](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L28) *** ### userId [Section titled “userId”](#userid) > **userId**: `string` | `null` Defined in: [packages/client/src/activity.ts:41](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L41) `null` when the row was written under another audit key and can’t be read with this one. *** ### username [Section titled “username”](#username) > **username**: `string` | `null` Defined in: [packages/client/src/activity.ts:43](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L43) Text chosen by the user: render it as text. `null` when the bot sends IDs only. # ActivityTopUsers Defined in: [packages/client/src/activity.ts:59](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L59) The users who ran the most in a window: up to 25. ## Properties [Section titled “Properties”](#properties) ### rows [Section titled “rows”](#rows) > **rows**: `object`\[] Defined in: [packages/client/src/activity.ts:61](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L61) #### runs [Section titled “runs”](#runs) > **runs**: `number` #### userId [Section titled “userId”](#userid) > **userId**: `string` | `null` *** ### window [Section titled “window”](#window) > **window**: `"24h"` | `"7d"` Defined in: [packages/client/src/activity.ts:60](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L60) # AudienceQuery Defined in: [packages/client/src/specs.ts:167](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L167) Unique users per day, week and salt period, and how runs split by locale, install, context and member tier. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"audience"` Defined in: [packages/client/src/specs.ts:168](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L168) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:169](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L169) # AudienceResult Defined in: [packages/client/src/results.ts:279](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L279) Answer to an `audience` query. Users are counted per UTC day, as salted hashes that end with their salt period. ## Properties [Section titled “Properties”](#properties) ### daily [Section titled “daily”](#daily) > **daily**: `object`\[] Defined in: [packages/client/src/results.ts:280](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L280) #### day [Section titled “day”](#day) > **day**: `string` #### newUsers [Section titled “newUsers”](#newusers) > **newUsers**: `number` #### users [Section titled “users”](#users) > **users**: `number` *** ### periods [Section titled “periods”](#periods) > **periods**: `object`\[] Defined in: [packages/client/src/results.ts:283](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L283) Unique users per salt period. `final` once the period is over and its count can no longer change. #### final [Section titled “final”](#final) > **final**: `boolean` #### period [Section titled “period”](#period) > **period**: `string` #### users [Section titled “users”](#users-1) > **users**: `number` *** ### premiumShare [Section titled “premiumShare”](#premiumshare) > **premiumShare**: `number` | `null` Defined in: [packages/client/src/results.ts:289](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L289) Share of runs by users with an entitlement, 0 to 1. *** ### splits [Section titled “splits”](#splits) > **splits**: `Partial`<`Record`<`"locale"` | `"install"` | `"context"` | `"tier"`, [`NullableKeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/nullablekeycount/)\[]>> Defined in: [packages/client/src/results.ts:287](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L287) Runs by locale, install type, context and member tier: up to 15 values each. A dimension with no runs is absent. *** ### stickiness [Section titled “stickiness”](#stickiness) > **stickiness**: `number` | `null` Defined in: [packages/client/src/results.ts:285](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L285) Average daily users over the latest period’s users, 0 to 1. *** ### weekly [Section titled “weekly”](#weekly) > **weekly**: `object`\[] Defined in: [packages/client/src/results.ts:281](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L281) #### users [Section titled “users”](#users-2) > **users**: `number` #### week [Section titled “week”](#week) > **week**: `string` # BurstsQuery Defined in: [packages/client/src/specs.ts:191](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L191) Minutes in the last 14 days with far more runs than the median minute. ## Properties [Section titled “Properties”](#properties) ### factor? [Section titled “factor?”](#factor) > `optional` **factor?**: `number` Defined in: [packages/client/src/specs.ts:195](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L195) How many times the median counts as a burst. 2 to 50, default 5. *** ### kind [Section titled “kind”](#kind) > **kind**: `"bursts"` Defined in: [packages/client/src/specs.ts:192](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L192) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:193](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L193) # BurstsResult Defined in: [packages/client/src/results.ts:353](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L353) Answer to a `bursts` query: up to 100 minutes, the busiest first. ## Properties [Section titled “Properties”](#properties) ### rows [Section titled “rows”](#rows) > **rows**: `object`\[] Defined in: [packages/client/src/results.ts:354](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L354) #### median [Section titled “median”](#median) > **median**: `number` #### minute [Section titled “minute”](#minute) > **minute**: `string` #### runs [Section titled “runs”](#runs) > **runs**: `number` # CommandQuery Defined in: [packages/client/src/specs.ts:117](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L117) One command in depth. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"command"` Defined in: [packages/client/src/specs.ts:118](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L118) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/specs.ts:120](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L120) The command’s name, without the slash. *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:121](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L121) # CommandResult Defined in: [packages/client/src/results.ts:115](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L115) Answer to a `command` query. Read from single events, which the collector keeps for 7 to 90 days. ## Properties [Section titled “Properties”](#properties) ### channelTypes [Section titled “channelTypes”](#channeltypes) > **channelTypes**: [`KeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/)\[] Defined in: [packages/client/src/results.ts:158](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L158) Discord channel type numbers. *** ### components [Section titled “components”](#components) > **components**: `object`\[] Defined in: [packages/client/src/results.ts:163](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L163) Buttons and select menus on the command’s messages, by custom ID. #### key [Section titled “key”](#key) > **key**: `string` | `null` #### kind [Section titled “kind”](#kind) > **kind**: `string` #### value [Section titled “value”](#value) > **value**: `number` *** ### contexts [Section titled “contexts”](#contexts) > **contexts**: [`NullableKeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/nullablekeycount/)\[] Defined in: [packages/client/src/results.ts:156](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L156) `0` server, `1` bot DM, `2` private channel. *** ### from [Section titled “from”](#from) > **from**: `string` Defined in: [packages/client/src/results.ts:117](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L117) Where counting starts: the range’s `from`, or later when single events are no longer kept that far back. *** ### installs [Section titled “installs”](#installs) > **installs**: [`NullableKeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/nullablekeycount/)\[] Defined in: [packages/client/src/results.ts:154](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L154) `guild`, `user` or `both`. *** ### kinds [Section titled “kinds”](#kinds) > **kinds**: [`KeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/)\[] Defined in: [packages/client/src/results.ts:144](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L144) *** ### latencyHistogram [Section titled “latencyHistogram”](#latencyhistogram) > **latencyHistogram**: `number`\[] | `null` Defined in: [packages/client/src/results.ts:143](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L143) Time to the first response in 40 buckets on a log scale: bucket `i` ends at `60000 ** ((i + 1) / 39)` milliseconds. `null` when no run answered. *** ### locales [Section titled “locales”](#locales) > **locales**: [`KeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/)\[] Defined in: [packages/client/src/results.ts:159](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L159) *** ### memberTiers [Section titled “memberTiers”](#membertiers) > **memberTiers**: [`NullableKeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/nullablekeycount/)\[] Defined in: [packages/client/src/results.ts:152](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L152) `admin`, `manager`, `member` or `dm`. *** ### modals [Section titled “modals”](#modals) > **modals**: `object`\[] Defined in: [packages/client/src/results.ts:165](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L165) Modals the command opened, and how many were submitted. #### customId [Section titled “customId”](#customid) > **customId**: `string` #### shown [Section titled “shown”](#shown) > **shown**: `number` #### submitted [Section titled “submitted”](#submitted) > **submitted**: `number` *** ### options [Section titled “options”](#options) > **options**: [`KeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/)\[] Defined in: [packages/client/src/results.ts:148](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L148) Option names, by how many runs used them. *** ### optionValues [Section titled “optionValues”](#optionvalues) > **optionValues**: `object`\[] Defined in: [packages/client/src/results.ts:150](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L150) Values of the options the bot lists in `captureOptionValues`. #### option [Section titled “option”](#option) > **option**: `string` #### runs [Section titled “runs”](#runs) > **runs**: `number` #### value [Section titled “value”](#value-1) > **value**: `string` *** ### subcommands [Section titled “subcommands”](#subcommands) > **subcommands**: [`KeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/)\[] Defined in: [packages/client/src/results.ts:146](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L146) Subcommands, with their group in front (`config set`). *** ### topServers [Section titled “topServers”](#topservers) > **topServers**: `object`\[] Defined in: [packages/client/src/results.ts:161](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L161) The 10 servers that ran it most. `key` is the server’s ID. #### icon [Section titled “icon”](#icon) > **icon**: `string` | `null` #### key [Section titled “key”](#key-1) > **key**: `string` #### name [Section titled “name”](#name) > **name**: `string` | `null` #### value [Section titled “value”](#value-2) > **value**: `number` *** ### totals [Section titled “totals”](#totals) > **totals**: `object` Defined in: [packages/client/src/results.ts:119](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L119) Every figure is `null` when the command did not run in the range. #### deferRate [Section titled “deferRate”](#deferrate) > **deferRate**: `number` | `null` Share of runs answered with a deferral, 0 to 1. Prefix commands, which have no response, don’t count. #### ephemeralRate [Section titled “ephemeralRate”](#ephemeralrate) > **ephemeralRate**: `number` | `null` Share of runs answered ephemerally, 0 to 1. #### error [Section titled “error”](#error) > **error**: `number` | `null` #### firstSeen [Section titled “firstSeen”](#firstseen) > **firstSeen**: `string` | `null` #### handlerP95Ms [Section titled “handlerP95Ms”](#handlerp95ms) > **handlerP95Ms**: `number` | `null` 95th percentile of the handler’s run time, in milliseconds. #### lastSeen [Section titled “lastSeen”](#lastseen) > **lastSeen**: `string` | `null` #### noResponse [Section titled “noResponse”](#noresponse) > **noResponse**: `number` | `null` #### ok [Section titled “ok”](#ok) > **ok**: `number` | `null` #### over3sRate [Section titled “over3sRate”](#over3srate) > **over3sRate**: `number` | `null` Share of answered runs whose first response took more than 3 seconds. #### premiumShare [Section titled “premiumShare”](#premiumshare) > **premiumShare**: `number` | `null` Share of runs by users with an entitlement, 0 to 1. #### runs [Section titled “runs”](#runs-1) > **runs**: `number` | `null` #### timeout [Section titled “timeout”](#timeout) > **timeout**: `number` | `null` Runs whose first response missed Discord’s 3-second deadline. # CommandRow Defined in: [packages/client/src/results.ts:84](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L84) One command in the answer to a `commands` query. ## Properties [Section titled “Properties”](#properties) ### changePct [Section titled “changePct”](#changepct) > **changePct**: `number` | `null` Defined in: [packages/client/src/results.ts:90](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L90) Change against `previousRuns`, in percent. `null` when there were none. *** ### command [Section titled “command”](#command) > **command**: `string` Defined in: [packages/client/src/results.ts:85](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L85) *** ### errorRate [Section titled “errorRate”](#errorrate) > **errorRate**: `number` | `null` Defined in: [packages/client/src/results.ts:92](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L92) Share of runs that did not end `ok`, 0 to 1. `null` without runs. *** ### kinds [Section titled “kinds”](#kinds) > **kinds**: `string`\[] Defined in: [packages/client/src/results.ts:104](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L104) How the command ran or is registered: `chat_input`, `message_command` (prefix), `user_context`… *** ### lastUsed [Section titled “lastUsed”](#lastused) > **lastUsed**: `string` | `null` Defined in: [packages/client/src/results.ts:98](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L98) Start of the last hour (or day, in ranges that reach back more than 13 months) the command ran in. *** ### p95Ms [Section titled “p95Ms”](#p95ms) > **p95Ms**: `number` | `null` Defined in: [packages/client/src/results.ts:94](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L94) 95th percentile of the time to the first response, in milliseconds. *** ### previousRuns [Section titled “previousRuns”](#previousruns) > **previousRuns**: `number` Defined in: [packages/client/src/results.ts:88](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L88) Runs in the period of the same length just before the range. *** ### registered [Section titled “registered”](#registered) > **registered**: `boolean` Defined in: [packages/client/src/results.ts:102](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L102) Whether the bot has the command registered with Discord. `false` for prefix commands and removed commands. *** ### runs [Section titled “runs”](#runs) > **runs**: `number` Defined in: [packages/client/src/results.ts:86](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L86) *** ### servers [Section titled “servers”](#servers) > **servers**: `number` Defined in: [packages/client/src/results.ts:96](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L96) Servers the command ran in. *** ### uniqueUsersThisPeriod [Section titled “uniqueUsersThisPeriod”](#uniqueusersthisperiod) > **uniqueUsersThisPeriod**: `number` | `null` Defined in: [packages/client/src/results.ts:100](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L100) Unique users since `periodStart`. `null` until the hourly count has run. # CommandsQuery Defined in: [packages/client/src/specs.ts:111](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L111) Every command that ran or is registered, compared with the period before. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"commands"` Defined in: [packages/client/src/specs.ts:112](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L112) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:113](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L113) # CommandsResult Defined in: [packages/client/src/results.ts:108](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L108) Answer to a `commands` query: up to 500 commands, the most used first. ## Properties [Section titled “Properties”](#properties) ### periodStart [Section titled “periodStart”](#periodstart) > **periodStart**: `string` Defined in: [packages/client/src/results.ts:110](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L110) First day of the current salt period, which `uniqueUsersThisPeriod` counts from. *** ### rows [Section titled “rows”](#rows) > **rows**: [`CommandRow`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandrow/)\[] Defined in: [packages/client/src/results.ts:111](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L111) # EventPropKeys Defined in: [packages/client/src/results.ts:450](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L450) Answer to an `eventProps` query without `prop`: the event’s property names. ## Properties [Section titled “Properties”](#properties) ### keys [Section titled “keys”](#keys) > **keys**: `object`\[] Defined in: [packages/client/src/results.ts:452](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L452) #### count [Section titled “count”](#count) > **count**: `number` #### key [Section titled “key”](#key) > **key**: `string` *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/results.ts:451](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L451) # EventPropsQuery Defined in: [packages/client/src/specs.ts:225](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L225) One custom event’s property names or, with `prop`, the most common values of that property. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"eventProps"` Defined in: [packages/client/src/specs.ts:226](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L226) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/specs.ts:228](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L228) The custom event’s name. *** ### prop? [Section titled “prop?”](#prop) > `optional` **prop?**: `string` Defined in: [packages/client/src/specs.ts:230](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L230) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:229](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L229) # EventPropValues Defined in: [packages/client/src/results.ts:456](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L456) Answer to an `eventProps` query with `prop`: that property’s 50 most common values, as text. ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/results.ts:457](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L457) *** ### prop [Section titled “prop”](#prop) > **prop**: `string` Defined in: [packages/client/src/results.ts:458](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L458) *** ### values [Section titled “values”](#values) > **values**: `object`\[] Defined in: [packages/client/src/results.ts:459](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L459) #### count [Section titled “count”](#count) > **count**: `number` #### value [Section titled “value”](#value) > **value**: `string` # EventsQuery Defined in: [packages/client/src/specs.ts:219](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L219) The custom events sent with `track()`. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"events"` Defined in: [packages/client/src/specs.ts:220](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L220) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:221](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L221) # EventsResult Defined in: [packages/client/src/results.ts:445](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L445) Answer to an `events` query: up to 200 custom events, the most frequent first. ## Properties [Section titled “Properties”](#properties) ### rows [Section titled “rows”](#rows) > **rows**: `object`\[] Defined in: [packages/client/src/results.ts:446](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L446) #### count [Section titled “count”](#count) > **count**: `number` #### lastSeen [Section titled “lastSeen”](#lastseen) > **lastSeen**: `string` #### name [Section titled “name”](#name) > **name**: `string` #### users [Section titled “users”](#users) > **users**: `number` # Filter Defined in: [packages/client/src/specs.ts:51](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L51) Keeps the rows whose `field` is `value`, or one of up to 100 values with `op: 'in'` or an array. ## Properties [Section titled “Properties”](#properties) ### field [Section titled “field”](#field) > **field**: [`Dimension`](/Shardlens/reference/sdk/shardlens/client/type-aliases/dimension/) Defined in: [packages/client/src/specs.ts:52](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L52) *** ### op? [Section titled “op?”](#op) > `optional` **op?**: `"in"` | `"eq"` Defined in: [packages/client/src/specs.ts:54](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L54) Default `'eq'`. *** ### value [Section titled “value”](#value) > **value**: `string` | readonly `string`\[] Defined in: [packages/client/src/specs.ts:55](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L55) # FunnelQuery Defined in: [packages/client/src/specs.ts:234](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L234) How many people got through 2 to 5 steps, in order. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"funnel"` Defined in: [packages/client/src/specs.ts:235](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L235) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:237](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L237) *** ### steps [Section titled “steps”](#steps) > **steps**: readonly [`Step`](/Shardlens/reference/sdk/shardlens/client/type-aliases/step/)\[] Defined in: [packages/client/src/specs.ts:236](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L236) *** ### timezone? [Section titled “timezone?”](#timezone) > `optional` **timezone?**: `string` Defined in: [packages/client/src/specs.ts:241](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L241) IANA name the daily cohorts are cut in. Default `'UTC'`. *** ### windowHours? [Section titled “windowHours?”](#windowhours) > `optional` **windowHours?**: `number` Defined in: [packages/client/src/specs.ts:239](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L239) Every step must happen within this many hours of the first. 1 to 168, default 24. # FunnelResult Defined in: [packages/client/src/results.ts:466](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L466) Answer to a `funnel` query. ## Properties [Section titled “Properties”](#properties) ### cohorts [Section titled “cohorts”](#cohorts) > **cohorts**: `object`\[] Defined in: [packages/client/src/results.ts:479](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L479) People by the day they entered the funnel. `users[i]` reached step `i + 1`. #### day [Section titled “day”](#day) > **day**: `string` #### users [Section titled “users”](#users) > **users**: `number`\[] *** ### steps [Section titled “steps”](#steps) > **steps**: `object`\[] Defined in: [packages/client/src/results.ts:470](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L470) The steps as asked, with the people who reached each and their median time from the first step. #### label [Section titled “label”](#label) > **label**: `string` #### medianSeconds [Section titled “medianSeconds”](#medianseconds) > **medianSeconds**: `number` | `null` `null` for the first step, and for a step nobody reached. #### name [Section titled “name”](#name) > **name**: `string` #### type [Section titled “type”](#type) > **type**: `"event"` | `"command"` #### users [Section titled “users”](#users-1) > **users**: `number` *** ### timezone [Section titled “timezone”](#timezone) > **timezone**: `string` Defined in: [packages/client/src/results.ts:468](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L468) *** ### windowHours [Section titled “windowHours”](#windowhours) > **windowHours**: `number` Defined in: [packages/client/src/results.ts:467](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L467) # GaugeQuery Defined in: [packages/client/src/specs.ts:178](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L178) A gauge over time, such as `shard.ping_ms`, `shard.guilds` or `memory.rss_bytes`. ## Properties [Section titled “Properties”](#properties) ### interval [Section titled “interval”](#interval) > **interval**: `"day"` | `"minute"` | `"hour"` Defined in: [packages/client/src/specs.ts:183](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L183) Minute series cover 2 days at most. *** ### kind [Section titled “kind”](#kind) > **kind**: `"gauge"` Defined in: [packages/client/src/specs.ts:179](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L179) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/specs.ts:180](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L180) *** ### perShard? [Section titled “perShard?”](#pershard) > `optional` **perShard?**: `boolean` Defined in: [packages/client/src/specs.ts:185](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L185) One line per shard instead of one for the bot. Default `false`. *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:181](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L181) *** ### timezone? [Section titled “timezone?”](#timezone) > `optional` **timezone?**: `string` Defined in: [packages/client/src/specs.ts:187](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L187) IANA name the points are cut in. Default `'UTC'`. # GaugeResult Defined in: [packages/client/src/results.ts:337](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L337) Answer to a `gauge` query. ## Properties [Section titled “Properties”](#properties) ### points [Section titled “points”](#points) > **points**: `object`\[] Defined in: [packages/client/src/results.ts:340](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L340) #### max [Section titled “max”](#max) > **max**: `number` Highest minute in the interval. #### shard [Section titled “shard”](#shard) > **shard**: `number` | `null` The shard, with `perShard`. Otherwise `null`. #### t [Section titled “t”](#t) > **t**: `string` Start of the interval in `timezone`, without an offset: `2026-11-16T00:00:00`. #### value [Section titled “value”](#value) > **value**: `number` Average over the interval. *** ### timezone [Section titled “timezone”](#timezone) > **timezone**: `string` Defined in: [packages/client/src/results.ts:339](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L339) The time zone the points are cut in. # GrowthQuery Defined in: [packages/client/src/specs.ts:159](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L159) Servers joined and left, activation, cohorts and how long servers stay. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"growth"` Defined in: [packages/client/src/specs.ts:160](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L160) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:161](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L161) *** ### timezone? [Section titled “timezone?”](#timezone) > `optional` **timezone?**: `string` Defined in: [packages/client/src/specs.ts:163](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L163) IANA name the days are cut in. Default `'UTC'`. # GrowthResult Defined in: [packages/client/src/results.ts:253](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L253) Answer to a `growth` query. ## Properties [Section titled “Properties”](#properties) ### activation [Section titled “activation”](#activation) > **activation**: `object` Defined in: [packages/client/src/results.ts:265](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L265) Servers that joined in the range, and how many ran a command within 24 hours. #### activated [Section titled “activated”](#activated) > **activated**: `number` #### joined [Section titled “joined”](#joined) > **joined**: `number` #### rate [Section titled “rate”](#rate) > **rate**: `number` | `null` *** ### approximateGuilds [Section titled “approximateGuilds”](#approximateguilds) > **approximateGuilds**: `object`\[] Defined in: [packages/client/src/results.ts:273](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L273) Discord’s own approximate server count, per day. #### day [Section titled “day”](#day) > **day**: `string` #### value [Section titled “value”](#value) > **value**: `number` *** ### cohorts [Section titled “cohorts”](#cohorts) > **cohorts**: `object`\[] Defined in: [packages/client/src/results.ts:269](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L269) Servers that joined in the same week (`cohort`) and ran a command `week` weeks later. #### cohort [Section titled “cohort”](#cohort) > **cohort**: `string` #### servers [Section titled “servers”](#servers) > **servers**: `number` #### week [Section titled “week”](#week) > **week**: `number` *** ### daily [Section titled “daily”](#daily) > **daily**: `object`\[] Defined in: [packages/client/src/results.ts:255](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L255) Days with a join or a leave. The `Detected` figures are those the bot found at startup, having been offline. #### day [Section titled “day”](#day-1) > **day**: `string` #### joins [Section titled “joins”](#joins) > **joins**: `number` | `null` #### joinsDetected [Section titled “joinsDetected”](#joinsdetected) > **joinsDetected**: `number` | `null` #### leaves [Section titled “leaves”](#leaves) > **leaves**: `number` | `null` #### leavesDetected [Section titled “leavesDetected”](#leavesdetected) > **leavesDetected**: `number` | `null` *** ### installs [Section titled “installs”](#installs) > **installs**: `object` Defined in: [packages/client/src/results.ts:267](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L267) Servers the bot is in now. `inactive` ran no command in the last 30 days. #### active [Section titled “active”](#active) > **active**: `number` #### inactive [Section titled “inactive”](#inactive) > **inactive**: `number` *** ### lifetimes [Section titled “lifetimes”](#lifetimes) > **lifetimes**: `object`\[] Defined in: [packages/client/src/results.ts:271](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L271) How long the servers that left in the range had stayed. #### bucket [Section titled “bucket”](#bucket) > **bucket**: `"<1d"` | `"1-7d"` | `"7-30d"` | `"30-90d"` | `"90d+"` #### servers [Section titled “servers”](#servers-1) > **servers**: `number` *** ### serverCount [Section titled “serverCount”](#servercount) > **serverCount**: `object` Defined in: [packages/client/src/results.ts:275](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L275) The collector’s count against Discord’s. `warn` when they are more than 2% apart. #### at [Section titled “at”](#at) > **at**: `string` | `null` #### discord [Section titled “discord”](#discord) > **discord**: `number` | `null` #### drift [Section titled “drift”](#drift) > **drift**: `number` | `null` #### ours [Section titled “ours”](#ours) > **ours**: `number` #### warn [Section titled “warn”](#warn) > **warn**: `boolean` *** ### sizeAtInstall [Section titled “sizeAtInstall”](#sizeatinstall) > **sizeAtInstall**: `object`\[] Defined in: [packages/client/src/results.ts:263](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L263) Servers that joined in the range, by member count when they did. #### bucket [Section titled “bucket”](#bucket-1) > **bucket**: `"1-10"` | `"11-100"` | `"101-1k"` | `"1k-10k"` | `"10k+"` #### servers [Section titled “servers”](#servers-2) > **servers**: `number` # HeatmapQuery Defined in: [packages/client/src/specs.ts:99](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L99) Counts by weekday and hour of the day. ## Properties [Section titled “Properties”](#properties) ### filters? [Section titled “filters?”](#filters) > `optional` **filters?**: readonly [`Filter`](/Shardlens/reference/sdk/shardlens/client/interfaces/filter/)\[] Defined in: [packages/client/src/specs.ts:105](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L105) Up to 10. *** ### kind [Section titled “kind”](#kind) > **kind**: `"heatmap"` Defined in: [packages/client/src/specs.ts:100](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L100) *** ### metric? [Section titled “metric?”](#metric) > `optional` **metric?**: [`SeriesMetric`](/Shardlens/reference/sdk/shardlens/client/type-aliases/seriesmetric/) Defined in: [packages/client/src/specs.ts:102](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L102) Default `'interactions'`. *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:103](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L103) *** ### timezone? [Section titled “timezone?”](#timezone) > `optional` **timezone?**: `string` Defined in: [packages/client/src/specs.ts:107](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L107) IANA name the weekdays and hours are in. Default `'UTC'`. # HeatmapResult Defined in: [packages/client/src/results.ts:68](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L68) Answer to a `heatmap` query. ## Properties [Section titled “Properties”](#properties) ### cells [Section titled “cells”](#cells) > **cells**: `object`\[] Defined in: [packages/client/src/results.ts:74](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L74) Only the cells that have something in them. #### hour [Section titled “hour”](#hour) > **hour**: `number` 0 to 23. #### value [Section titled “value”](#value) > **value**: `number` #### weekday [Section titled “weekday”](#weekday) > **weekday**: `number` ISO weekday: 1 is Monday, 7 is Sunday. *** ### source? [Section titled “source?”](#source) > `optional` **source?**: `"clickhouse"` Defined in: [packages/client/src/results.ts:72](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L72) Set when a ClickHouse analytics store answered instead of PostgreSQL. *** ### timezone [Section titled “timezone”](#timezone) > **timezone**: `string` Defined in: [packages/client/src/results.ts:70](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L70) The time zone the weekdays and hours are in. # InstallsQuery Defined in: [packages/client/src/specs.ts:211](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L211) User installs and removals, from Discord’s webhook events. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"installs"` Defined in: [packages/client/src/specs.ts:212](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L212) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:213](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L213) *** ### timezone? [Section titled “timezone?”](#timezone) > `optional` **timezone?**: `string` Defined in: [packages/client/src/specs.ts:215](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L215) IANA name the days are cut in. Default `'UTC'`. # InstallsResult Defined in: [packages/client/src/results.ts:434](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L434) Answer to an `installs` query. ## Properties [Section titled “Properties”](#properties) ### approximateUserInstalls [Section titled “approximateUserInstalls”](#approximateuserinstalls) > **approximateUserInstalls**: `object`\[] Defined in: [packages/client/src/results.ts:439](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L439) Discord’s own approximate count of user installs, per day. #### day [Section titled “day”](#day) > **day**: `string` #### value [Section titled “value”](#value) > **value**: `number` *** ### daily [Section titled “daily”](#daily) > **daily**: `object`\[] Defined in: [packages/client/src/results.ts:435](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L435) #### day [Section titled “day”](#day-1) > **day**: `string` #### serverInstalls [Section titled “serverInstalls”](#serverinstalls) > **serverInstalls**: `number` #### userInstalls [Section titled “userInstalls”](#userinstalls) > **userInstalls**: `number` #### userRemovals [Section titled “userRemovals”](#userremovals) > **userRemovals**: `number` *** ### scopes [Section titled “scopes”](#scopes) > **scopes**: `object`\[] Defined in: [packages/client/src/results.ts:437](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L437) OAuth2 scopes granted at install. #### installs [Section titled “installs”](#installs) > **installs**: `number` #### scope [Section titled “scope”](#scope) > **scope**: `string` *** ### webhookStatus [Section titled “webhookStatus”](#webhookstatus) > **webhookStatus**: `number` | `null` Defined in: [packages/client/src/results.ts:441](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L441) Discord’s webhook events status: 1 disabled, 2 enabled, 3 disabled by Discord. `null` until the bot reports it. # KeyCount Defined in: [packages/client/src/results.ts:7](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L7) One value of a dimension and how often it occurred. ## Properties [Section titled “Properties”](#properties) ### key [Section titled “key”](#key) > **key**: `string` Defined in: [packages/client/src/results.ts:8](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L8) *** ### value [Section titled “value”](#value) > **value**: `number` Defined in: [packages/client/src/results.ts:9](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L9) # LiveUpdate Defined in: [packages/client/src/results.ts:536](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L536) One update of the live stream: what the bot is doing right now. ## Properties [Section titled “Properties”](#properties) ### activeShards [Section titled “activeShards”](#activeshards) > **activeShards**: `number` Defined in: [packages/client/src/results.ts:548](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L548) *** ### errors15m [Section titled “errors15m”](#errors15m) > **errors15m**: `number` Defined in: [packages/client/src/results.ts:541](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L541) Failed runs in the last 15 minutes. *** ### p95Ms5m [Section titled “p95Ms5m”](#p95ms5m) > **p95Ms5m**: `number` | `null` Defined in: [packages/client/src/results.ts:545](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L545) 95th percentile of the time to the first response over the last 5 minutes, in milliseconds. *** ### perMinute [Section titled “perMinute”](#perminute) > **perMinute**: `number` Defined in: [packages/client/src/results.ts:539](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L539) Command runs in the last 60 seconds. *** ### perSecond [Section titled “perSecond”](#persecond) > **perSecond**: `number`\[] Defined in: [packages/client/src/results.ts:543](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L543) Runs in each of the last 60 seconds, oldest first. Empty until the collector has seen a run. *** ### servers [Section titled “servers”](#servers) > **servers**: `number` Defined in: [packages/client/src/results.ts:551](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L551) Servers the bot is in now. *** ### shards [Section titled “shards”](#shards) > **shards**: `object`\[] Defined in: [packages/client/src/results.ts:547](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L547) Each shard’s latest ping in the last hour. `fresh` when it is under 2 minutes old. #### fresh [Section titled “fresh”](#fresh) > **fresh**: `boolean` #### ping [Section titled “ping”](#ping) > **ping**: `number` #### shard [Section titled “shard”](#shard) > **shard**: `number` *** ### staleShards [Section titled “staleShards”](#staleshards) > **staleShards**: `number`\[] Defined in: [packages/client/src/results.ts:549](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L549) *** ### ts [Section titled “ts”](#ts) > **ts**: `string` Defined in: [packages/client/src/results.ts:537](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L537) # Meta Defined in: [packages/client/src/results.ts:520](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L520) What `GET /v1/meta` answers: the app and how its collector is set up. ## Properties [Section titled “Properties”](#properties) ### appId [Section titled “appId”](#appid) > **appId**: `string` Defined in: [packages/client/src/results.ts:521](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L521) *** ### auditKeyConfigured [Section titled “auditKeyConfigured”](#auditkeyconfigured) > **auditKeyConfigured**: `boolean` Defined in: [packages/client/src/results.ts:530](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L530) *** ### discordLogin [Section titled “discordLogin”](#discordlogin) > **discordLogin**: `boolean` Defined in: [packages/client/src/results.ts:531](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L531) *** ### mode [Section titled “mode”](#mode) > **mode**: `"privacy"` | `"audit"` Defined in: [packages/client/src/results.ts:524](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L524) `audit` when the collector records who ran what. *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/results.ts:522](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L522) *** ### rawRetentionDays [Section titled “rawRetentionDays”](#rawretentiondays) > **rawRetentionDays**: `number` Defined in: [packages/client/src/results.ts:529](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L529) How long single events are kept, in days. *** ### saltPeriod [Section titled “saltPeriod”](#saltperiod) > **saltPeriod**: `"day"` | `"week"` | `"month"` Defined in: [packages/client/src/results.ts:525](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L525) *** ### timezone [Section titled “timezone”](#timezone) > **timezone**: `string` Defined in: [packages/client/src/results.ts:527](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L527) The time zone chosen in Settings, for charts. *** ### webhookEventsConfigured [Section titled “webhookEventsConfigured”](#webhookeventsconfigured) > **webhookEventsConfigured**: `boolean` Defined in: [packages/client/src/results.ts:532](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L532) # NullableKeyCount Defined in: [packages/client/src/results.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L13) As [KeyCount](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/), for a dimension an event may not have: `key` is `null` for the events without it. ## Properties [Section titled “Properties”](#properties) ### key [Section titled “key”](#key) > **key**: `string` | `null` Defined in: [packages/client/src/results.ts:14](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L14) *** ### value [Section titled “value”](#value) > **value**: `number` Defined in: [packages/client/src/results.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L15) # OverviewQuery Defined in: [packages/client/src/specs.ts:173](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L173) The bot at a glance: the last 30 days of runs, servers, users, and whether events are arriving. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"overview"` Defined in: [packages/client/src/specs.ts:174](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L174) # OverviewResult Defined in: [packages/client/src/results.ts:293](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L293) Answer to an `overview` query. ## Properties [Section titled “Properties”](#properties) ### app [Section titled “app”](#app) > **app**: { `id`: `string`; `mode`: `"privacy"` | `"audit"`; `name`: `string`; `rawRetentionDays`: `number`; `saltPeriod`: `"day"` | `"week"` | `"month"`; `timezone`: `string`; } | `null` Defined in: [packages/client/src/results.ts:294](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L294) *** ### appInfo [Section titled “appInfo”](#appinfo) > **appInfo**: { `approxGuilds`: `number` | `null`; `approxUserAuthorizations`: `number` | `null`; `approxUserInstalls`: `number` | `null`; `eventWebhooksStatus`: `number` | `null`; `libVersion`: `string` | `null`; `name`: `string`; `nodeVersion`: `string` | `null`; `release`: `string` | `null`; `sdkVersion`: `string` | `null`; `sessionStartRemaining`: `number` | `null`; `sessionStartTotal`: `number` | `null`; `ts`: `string`; } | `null` Defined in: [packages/client/src/results.ts:303](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L303) What the bot last reported about its application. `null` until it has. #### Union Members [Section titled “Union Members”](#union-members) ##### Type Literal [Section titled “Type Literal”](#type-literal) { `approxGuilds`: `number` | `null`; `approxUserAuthorizations`: `number` | `null`; `approxUserInstalls`: `number` | `null`; `eventWebhooksStatus`: `number` | `null`; `libVersion`: `string` | `null`; `name`: `string`; `nodeVersion`: `string` | `null`; `release`: `string` | `null`; `sdkVersion`: `string` | `null`; `sessionStartRemaining`: `number` | `null`; `sessionStartTotal`: `number` | `null`; `ts`: `string`; } ##### approxGuilds [Section titled “approxGuilds”](#approxguilds) > **approxGuilds**: `number` | `null` ##### approxUserAuthorizations [Section titled “approxUserAuthorizations”](#approxuserauthorizations) > **approxUserAuthorizations**: `number` | `null` ##### approxUserInstalls [Section titled “approxUserInstalls”](#approxuserinstalls) > **approxUserInstalls**: `number` | `null` ##### eventWebhooksStatus [Section titled “eventWebhooksStatus”](#eventwebhooksstatus) > **eventWebhooksStatus**: `number` | `null` Discord’s webhook events status: 1 disabled, 2 enabled, 3 disabled by Discord. ##### libVersion [Section titled “libVersion”](#libversion) > **libVersion**: `string` | `null` ##### name [Section titled “name”](#name) > **name**: `string` ##### nodeVersion [Section titled “nodeVersion”](#nodeversion) > **nodeVersion**: `string` | `null` ##### release [Section titled “release”](#release) > **release**: `string` | `null` ##### sdkVersion [Section titled “sdkVersion”](#sdkversion) > **sdkVersion**: `string` | `null` ##### sessionStartRemaining [Section titled “sessionStartRemaining”](#sessionstartremaining) > **sessionStartRemaining**: `number` | `null` ##### sessionStartTotal [Section titled “sessionStartTotal”](#sessionstarttotal) > **sessionStartTotal**: `number` | `null` ##### ts [Section titled “ts”](#ts) > **ts**: `string` *** `null` *** ### checklist [Section titled “checklist”](#checklist) > **checklist**: `object` Defined in: [packages/client/src/results.ts:328](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L328) #### appInfoReceived [Section titled “appInfoReceived”](#appinforeceived) > **appInfoReceived**: `boolean` #### receivingEvents [Section titled “receivingEvents”](#receivingevents) > **receivingEvents**: `boolean` #### requiredPermissionsSet [Section titled “requiredPermissionsSet”](#requiredpermissionsset) > **requiredPermissionsSet**: `boolean` #### webhookEventsEnabled [Section titled “webhookEventsEnabled”](#webhookeventsenabled) > **webhookEventsEnabled**: `boolean` *** ### lastEventAt [Section titled “lastEventAt”](#lasteventat) > **lastEventAt**: `string` | `null` Defined in: [packages/client/src/results.ts:327](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L327) Start of the last minute an event arrived in, within the last 14 days. *** ### periodStart [Section titled “periodStart”](#periodstart) > **periodStart**: `string` Defined in: [packages/client/src/results.ts:325](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L325) First day of the current salt period. *** ### runs30d [Section titled “runs30d”](#runs30d) > **runs30d**: `object`\[] Defined in: [packages/client/src/results.ts:320](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L320) UTC days with runs in the last 30. #### day [Section titled “day”](#day) > **day**: `string` #### failures [Section titled “failures”](#failures) > **failures**: `number` | `null` #### runs [Section titled “runs”](#runs) > **runs**: `number` *** ### sdkInstances [Section titled “sdkInstances”](#sdkinstances) > **sdkInstances**: [`SdkInstance`](/Shardlens/reference/sdk/shardlens/client/interfaces/sdkinstance/)\[] Defined in: [packages/client/src/results.ts:318](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L318) *** ### servers [Section titled “servers”](#servers) > **servers**: `number` Defined in: [packages/client/src/results.ts:322](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L322) Servers the bot is in now. *** ### uniqueUsersThisPeriod [Section titled “uniqueUsersThisPeriod”](#uniqueusersthisperiod) > **uniqueUsersThisPeriod**: `number` | `null` Defined in: [packages/client/src/results.ts:323](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L323) # PremiumQuery Defined in: [packages/client/src/specs.ts:205](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L205) Entitlements and subscriptions by SKU, and the premium share of runs. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"premium"` Defined in: [packages/client/src/specs.ts:206](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L206) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:207](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L207) # PremiumResult Defined in: [packages/client/src/results.ts:413](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L413) Answer to a `premium` query. ## Properties [Section titled “Properties”](#properties) ### activeEntitlements [Section titled “activeEntitlements”](#activeentitlements) > **activeEntitlements**: `object`\[] Defined in: [packages/client/src/results.ts:416](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L416) #### active [Section titled “active”](#active) > **active**: `number` #### name [Section titled “name”](#name) > **name**: `string` #### sku [Section titled “sku”](#sku) > **sku**: `string` *** ### changes [Section titled “changes”](#changes) > **changes**: `object`\[] Defined in: [packages/client/src/results.ts:415](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L415) Entitlements created, updated and deleted in the range. `testCount` of them were test entitlements. #### action [Section titled “action”](#action) > **action**: `string` #### count [Section titled “count”](#count) > **count**: `number` #### name [Section titled “name”](#name-1) > **name**: `string` #### sku [Section titled “sku”](#sku-1) > **sku**: `string` #### testCount [Section titled “testCount”](#testcount) > **testCount**: `number` *** ### estimatedMonthlyRevenue [Section titled “estimatedMonthlyRevenue”](#estimatedmonthlyrevenue) > **estimatedMonthlyRevenue**: `Record`<`string`, `number`> Defined in: [packages/client/src/results.ts:429](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L429) By currency: active and ending subscriptions times their price. *** ### premiumShare [Section titled “premiumShare”](#premiumshare) > **premiumShare**: `number` | `null` Defined in: [packages/client/src/results.ts:427](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L427) Share of runs by users with an entitlement, 0 to 1. *** ### pricesConfigured [Section titled “pricesConfigured”](#pricesconfigured) > **pricesConfigured**: `boolean` Defined in: [packages/client/src/results.ts:430](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L430) *** ### subscriptions [Section titled “subscriptions”](#subscriptions) > **subscriptions**: `object`\[] Defined in: [packages/client/src/results.ts:418](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L418) Subscriptions by SKU, with the price set in Settings. #### active [Section titled “active”](#active-1) > **active**: `number` #### ending [Section titled “ending”](#ending) > **ending**: `number` #### inactive [Section titled “inactive”](#inactive) > **inactive**: `number` #### name [Section titled “name”](#name-2) > **name**: `string` #### price [Section titled “price”](#price) > **price**: { `amount`: `number`; `currency`: `string`; } | `null` #### sku [Section titled “sku”](#sku-2) > **sku**: `string` # QueryResults Defined in: [packages/client/src/results.ts:497](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L497) The answer each query `kind` gets. ## Properties [Section titled “Properties”](#properties) ### audience [Section titled “audience”](#audience) > **audience**: [`AudienceResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/audienceresult/) Defined in: [packages/client/src/results.ts:506](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L506) *** ### bursts [Section titled “bursts”](#bursts) > **bursts**: [`BurstsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/burstsresult/) Defined in: [packages/client/src/results.ts:509](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L509) *** ### command [Section titled “command”](#command) > **command**: [`CommandResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandresult/) Defined in: [packages/client/src/results.ts:502](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L502) *** ### commands [Section titled “commands”](#commands) > **commands**: [`CommandsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandsresult/) Defined in: [packages/client/src/results.ts:501](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L501) *** ### eventProps [Section titled “eventProps”](#eventprops) > **eventProps**: [`EventPropsResult`](/Shardlens/reference/sdk/shardlens/client/type-aliases/eventpropsresult/) Defined in: [packages/client/src/results.ts:514](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L514) *** ### events [Section titled “events”](#events) > **events**: [`EventsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventsresult/) Defined in: [packages/client/src/results.ts:513](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L513) *** ### funnel [Section titled “funnel”](#funnel) > **funnel**: [`FunnelResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/funnelresult/) Defined in: [packages/client/src/results.ts:515](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L515) *** ### gauge [Section titled “gauge”](#gauge) > **gauge**: [`GaugeResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/gaugeresult/) Defined in: [packages/client/src/results.ts:508](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L508) *** ### growth [Section titled “growth”](#growth) > **growth**: [`GrowthResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/growthresult/) Defined in: [packages/client/src/results.ts:505](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L505) *** ### heatmap [Section titled “heatmap”](#heatmap) > **heatmap**: [`HeatmapResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/heatmapresult/) Defined in: [packages/client/src/results.ts:500](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L500) *** ### installs [Section titled “installs”](#installs) > **installs**: [`InstallsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/installsresult/) Defined in: [packages/client/src/results.ts:512](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L512) *** ### overview [Section titled “overview”](#overview) > **overview**: [`OverviewResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/overviewresult/) Defined in: [packages/client/src/results.ts:507](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L507) *** ### premium [Section titled “premium”](#premium) > **premium**: [`PremiumResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/premiumresult/) Defined in: [packages/client/src/results.ts:511](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L511) *** ### reliability [Section titled “reliability”](#reliability) > **reliability**: [`ReliabilityResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/reliabilityresult/) Defined in: [packages/client/src/results.ts:510](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L510) *** ### retention [Section titled “retention”](#retention) > **retention**: [`RetentionResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/retentionresult/) Defined in: [packages/client/src/results.ts:516](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L516) *** ### series [Section titled “series”](#series) > **series**: [`SeriesResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/seriesresult/) Defined in: [packages/client/src/results.ts:498](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L498) *** ### server [Section titled “server”](#server) > **server**: [`ServerResult`](/Shardlens/reference/sdk/shardlens/client/type-aliases/serverresult/) Defined in: [packages/client/src/results.ts:504](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L504) *** ### servers [Section titled “servers”](#servers) > **servers**: [`ServersResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/serversresult/) Defined in: [packages/client/src/results.ts:503](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L503) *** ### top [Section titled “top”](#top) > **top**: [`TopResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/topresult/) Defined in: [packages/client/src/results.ts:499](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L499) # ReliabilityQuery Defined in: [packages/client/src/specs.ts:199](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L199) Missed deadlines, errors, REST calls, rate limits, shards and the SDK’s own health. ## Properties [Section titled “Properties”](#properties) ### kind [Section titled “kind”](#kind) > **kind**: `"reliability"` Defined in: [packages/client/src/specs.ts:200](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L200) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:201](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L201) # ReliabilityResult Defined in: [packages/client/src/results.ts:358](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L358) Answer to a `reliability` query. Prefix commands, which have no response or deadline, are left out. ## Properties [Section titled “Properties”](#properties) ### errorsByCode [Section titled “errorsByCode”](#errorsbycode) > **errorsByCode**: [`KeyCount`](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/)\[] Defined in: [packages/client/src/results.ts:374](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L374) Failed runs by Discord API error code or, without one, by error class. *** ### from [Section titled “from”](#from) > **from**: `string` Defined in: [packages/client/src/results.ts:360](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L360) Where counting single events starts: the range’s `from`, or later when they are no longer kept that far back. *** ### identify [Section titled “identify”](#identify) > **identify**: { `libVersion`: `string` | `null`; `nodeVersion`: `string` | `null`; `release`: `string` | `null`; `remaining`: `number` | `null`; `sdkVersion`: `string` | `null`; `total`: `number` | `null`; `ts`: `string`; } | `null` Defined in: [packages/client/src/results.ts:389](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L389) Gateway session starts left today, and the versions the bot runs. `null` until the bot has reported them. *** ### invalidBudget [Section titled “invalidBudget”](#invalidbudget) > **invalidBudget**: `object` Defined in: [packages/client/src/results.ts:387](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L387) 401, 403 and 429 answers in the last 10 minutes, against Discord’s limit of 10,000. #### limit [Section titled “limit”](#limit) > **limit**: `number` #### share [Section titled “share”](#share) > **share**: `number` #### shared429 [Section titled “shared429”](#shared429) > **shared429**: `number` #### used [Section titled “used”](#used) > **used**: `number` *** ### process [Section titled “process”](#process) > **process**: `Partial`<`Record`<`"eventloop.p99_ms"` | `"memory.rss_bytes"` | `"memory.heap_used_bytes"` | `"cache.users"` | `"cache.channels"`, `number`>> Defined in: [packages/client/src/results.ts:403](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L403) The bot’s latest process gauges, added up over its processes (the worst process for event-loop delay). *** ### rateLimits [Section titled “rateLimits”](#ratelimits) > **rateLimits**: `object`\[] Defined in: [packages/client/src/results.ts:385](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L385) Rate limits the bot ran into. `maxRetryAfter` is in milliseconds. #### count [Section titled “count”](#count) > **count**: `number` #### maxRetryAfter [Section titled “maxRetryAfter”](#maxretryafter) > **maxRetryAfter**: `number` | `null` #### route [Section titled “route”](#route) > **route**: `string` #### scope [Section titled “scope”](#scope) > **scope**: `string` *** ### routes [Section titled “routes”](#routes) > **routes**: `object`\[] Defined in: [packages/client/src/results.ts:376](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L376) REST calls by method and route. `failures` are answers of 400 and above. #### calls [Section titled “calls”](#calls) > **calls**: `number` #### failures [Section titled “failures”](#failures) > **failures**: `number` | `null` #### method [Section titled “method”](#method) > **method**: `string` #### p95Ms [Section titled “p95Ms”](#p95ms) > **p95Ms**: `number` | `null` #### retries [Section titled “retries”](#retries) > **retries**: `number` #### route [Section titled “route”](#route-1) > **route**: `string` *** ### sdkInstances [Section titled “sdkInstances”](#sdkinstances) > **sdkInstances**: [`SdkInstance`](/Shardlens/reference/sdk/shardlens/client/interfaces/sdkinstance/)\[] Defined in: [packages/client/src/results.ts:409](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L409) *** ### shardEvents [Section titled “shardEvents”](#shardevents) > **shardEvents**: `object`\[] Defined in: [packages/client/src/results.ts:401](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L401) The last 50 gateway state changes in the range. #### closeCode [Section titled “closeCode”](#closecode) > **closeCode**: `number` | `null` #### replayed [Section titled “replayed”](#replayed) > **replayed**: `number` | `null` #### shard [Section titled “shard”](#shard) > **shard**: `number` #### state [Section titled “state”](#state) > **state**: `string` #### ts [Section titled “ts”](#ts) > **ts**: `string` *** ### shards [Section titled “shards”](#shards) > **shards**: `object`\[] Defined in: [packages/client/src/results.ts:399](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L399) Each shard’s latest ping in the last day. `stale` when it is more than 2 minutes old. #### ping [Section titled “ping”](#ping) > **ping**: `number` #### shard [Section titled “shard”](#shard-1) > **shard**: `number` #### stale [Section titled “stale”](#stale) > **stale**: `boolean` #### ts [Section titled “ts”](#ts-1) > **ts**: `string` *** ### totals [Section titled “totals”](#totals) > **totals**: `object` Defined in: [packages/client/src/results.ts:362](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L362) Every figure is `null` when nothing ran in the range. #### errors [Section titled “errors”](#errors) > **errors**: `number` | `null` #### missedDeadlines [Section titled “missedDeadlines”](#misseddeadlines) > **missedDeadlines**: `number` | `null` Runs that answered after 3 seconds or not at all. #### noResponse [Section titled “noResponse”](#noresponse) > **noResponse**: `number` | `null` #### over3sRate [Section titled “over3sRate”](#over3srate) > **over3sRate**: `number` | `null` #### p50Ms [Section titled “p50Ms”](#p50ms) > **p50Ms**: `number` | `null` #### p95Ms [Section titled “p95Ms”](#p95ms-1) > **p95Ms**: `number` | `null` #### p99Ms [Section titled “p99Ms”](#p99ms) > **p99Ms**: `number` | `null` #### runs [Section titled “runs”](#runs) > **runs**: `number` | `null` # RequestOptions Defined in: [packages/client/src/transport.ts:22](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/transport.ts#L22) Options of one call. ## Properties [Section titled “Properties”](#properties) ### signal? [Section titled “signal?”](#signal) > `optional` **signal?**: `AbortSignal` Defined in: [packages/client/src/transport.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/transport.ts#L27) Aborting ends the call. A request then rejects with the signal’s reason, as `fetch` does; a live stream just ends. # RetentionQuery Defined in: [packages/client/src/specs.ts:245](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L245) People who did `start`, by the day or week they first did, and how many came back in each later period. ## Properties [Section titled “Properties”](#properties) ### interval? [Section titled “interval?”](#interval) > `optional` **interval?**: `"day"` | `"week"` Defined in: [packages/client/src/specs.ts:252](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L252) Default `'week'`. *** ### kind [Section titled “kind”](#kind) > **kind**: `"retention"` Defined in: [packages/client/src/specs.ts:246](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L246) *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:250](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L250) *** ### return? [Section titled “return?”](#return) > `optional` **return?**: `"any"` | [`Step`](/Shardlens/reference/sdk/shardlens/client/type-aliases/step/) Defined in: [packages/client/src/specs.ts:249](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L249) What counts as coming back. Default `'any'`: any command or custom event. *** ### start [Section titled “start”](#start) > **start**: [`Step`](/Shardlens/reference/sdk/shardlens/client/type-aliases/step/) Defined in: [packages/client/src/specs.ts:247](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L247) *** ### timezone? [Section titled “timezone?”](#timezone) > `optional` **timezone?**: `string` Defined in: [packages/client/src/specs.ts:254](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L254) IANA name the cohorts are cut in. Default `'UTC'`. # RetentionResult Defined in: [packages/client/src/results.ts:483](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L483) Answer to a `retention` query. ## Properties [Section titled “Properties”](#properties) ### cohorts [Section titled “cohorts”](#cohorts) > **cohorts**: `object`\[] Defined in: [packages/client/src/results.ts:493](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L493) `retained[i]` of the `size` people who started in `cohort` came back `i + 1` periods later. #### cohort [Section titled “cohort”](#cohort) > **cohort**: `string` #### retained [Section titled “retained”](#retained) > **retained**: `number`\[] #### size [Section titled “size”](#size) > **size**: `number` *** ### interval [Section titled “interval”](#interval) > **interval**: `"day"` | `"week"` Defined in: [packages/client/src/results.ts:484](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L484) *** ### periods [Section titled “periods”](#periods) > **periods**: `number` Defined in: [packages/client/src/results.ts:491](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L491) Periods followed after the first: 14 days or 8 weeks. *** ### return [Section titled “return”](#return) > **return**: `string` Defined in: [packages/client/src/results.ts:489](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L489) The return step, as a label. *** ### start [Section titled “start”](#start) > **start**: `string` Defined in: [packages/client/src/results.ts:487](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L487) The start step, as a label. *** ### timezone [Section titled “timezone”](#timezone) > **timezone**: `string` Defined in: [packages/client/src/results.ts:485](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L485) # SdkInstance Defined in: [packages/client/src/results.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L19) One process of the bot, as the SDK last reported on itself. ## Properties [Section titled “Properties”](#properties) ### dropped [Section titled “dropped”](#dropped) > **dropped**: `Record`<`string`, `number`> Defined in: [packages/client/src/results.ts:28](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L28) Events the SDK gave up on, by reason. *** ### failedFlushes [Section titled “failedFlushes”](#failedflushes) > **failedFlushes**: `number` Defined in: [packages/client/src/results.ts:29](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L29) *** ### instance [Section titled “instance”](#instance) > **instance**: `string` Defined in: [packages/client/src/results.ts:20](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L20) *** ### internalErrors [Section titled “internalErrors”](#internalerrors) > **internalErrors**: `Record`<`string`, `number`> Defined in: [packages/client/src/results.ts:31](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L31) Errors caught inside the SDK, by where they happened. *** ### queueDepth [Section titled “queueDepth”](#queuedepth) > **queueDepth**: `number` Defined in: [packages/client/src/results.ts:26](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L26) Events waiting to be sent. *** ### sdkVersion [Section titled “sdkVersion”](#sdkversion) > **sdkVersion**: `string` | `null` Defined in: [packages/client/src/results.ts:32](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L32) *** ### shards [Section titled “shards”](#shards) > **shards**: `number`\[] Defined in: [packages/client/src/results.ts:24](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L24) The shards the process holds. *** ### ts [Section titled “ts”](#ts) > **ts**: `string` Defined in: [packages/client/src/results.ts:22](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L22) When it last reported. # SeriesQuery Defined in: [packages/client/src/specs.ts:65](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L65) A metric over time, optionally split by one dimension. ## Properties [Section titled “Properties”](#properties) ### filters? [Section titled “filters?”](#filters) > `optional` **filters?**: readonly [`Filter`](/Shardlens/reference/sdk/shardlens/client/interfaces/filter/)\[] Defined in: [packages/client/src/specs.ts:76](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L76) Up to 10. *** ### groupBy? [Section titled “groupBy?”](#groupby) > `optional` **groupBy?**: [`Dimension`](/Shardlens/reference/sdk/shardlens/client/type-aliases/dimension/) Defined in: [packages/client/src/specs.ts:73](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L73) *** ### interval [Section titled “interval”](#interval) > **interval**: `"day"` | `"week"` | `"month"` | `"minute"` | `"hour"` Defined in: [packages/client/src/specs.ts:72](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L72) Minute series cover 2 days at most, hourly series 31. *** ### kind [Section titled “kind”](#kind) > **kind**: `"series"` Defined in: [packages/client/src/specs.ts:66](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L66) *** ### limit? [Section titled “limit?”](#limit) > `optional` **limit?**: `number` Defined in: [packages/client/src/specs.ts:80](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L80) With `groupBy`: how many of its values to keep, the busiest first. 1 to 20, default 10. *** ### metric [Section titled “metric”](#metric) > **metric**: [`SeriesMetric`](/Shardlens/reference/sdk/shardlens/client/type-aliases/seriesmetric/) Defined in: [packages/client/src/specs.ts:67](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L67) *** ### name? [Section titled “name?”](#name) > `optional` **name?**: `string` Defined in: [packages/client/src/specs.ts:69](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L69) For `metric: 'custom'`: the event’s name. *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:70](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L70) *** ### stat? [Section titled “stat?”](#stat) > `optional` **stat?**: [`Stat`](/Shardlens/reference/sdk/shardlens/client/type-aliases/stat/) Defined in: [packages/client/src/specs.ts:74](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L74) *** ### timezone? [Section titled “timezone?”](#timezone) > `optional` **timezone?**: `string` Defined in: [packages/client/src/specs.ts:78](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L78) IANA name the points are cut in. Default `'UTC'`. # SeriesResult Defined in: [packages/client/src/results.ts:36](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L36) Answer to a `series` query. ## Properties [Section titled “Properties”](#properties) ### points [Section titled “points”](#points) > **points**: `object`\[] Defined in: [packages/client/src/results.ts:41](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L41) #### key [Section titled “key”](#key) > **key**: `string` | `null` The `groupBy` value (`''` for events without it), or `null` when the query has no `groupBy`. #### t [Section titled “t”](#t) > **t**: `string` Start of the interval in `timezone`, without an offset: `2026-11-16T00:00:00`. #### value [Section titled “value”](#value) > **value**: `number` | `null` `null` when the statistic has nothing to work from, such as a percentile of runs that never answered. *** ### source? [Section titled “source?”](#source) > `optional` **source?**: `"clickhouse"` Defined in: [packages/client/src/results.ts:40](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L40) Set when a ClickHouse analytics store answered instead of PostgreSQL. *** ### timezone [Section titled “timezone”](#timezone) > **timezone**: `string` Defined in: [packages/client/src/results.ts:38](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L38) The time zone the points are cut in. # ServerProfile Defined in: [packages/client/src/results.ts:201](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L201) A server’s profile, as the bot last saw it. ## Properties [Section titled “Properties”](#properties) ### baseline [Section titled “baseline”](#baseline) > **baseline**: `boolean` Defined in: [packages/client/src/results.ts:228](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L228) *** ### boosts [Section titled “boosts”](#boosts) > **boosts**: `number` | `null` Defined in: [packages/client/src/results.ts:212](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L212) *** ### botPermissions [Section titled “botPermissions”](#botpermissions) > **botPermissions**: `string` | `null` Defined in: [packages/client/src/results.ts:226](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L226) The bot’s permission bits in the server, as a decimal string. *** ### channelCounts [Section titled “channelCounts”](#channelcounts) > **channelCounts**: `Record`<`string`, `number`> | `null` Defined in: [packages/client/src/results.ts:221](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L221) Channels by Discord channel type number. *** ### createdAt [Section titled “createdAt”](#createdat) > **createdAt**: `string` | `null` Defined in: [packages/client/src/results.ts:216](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L216) *** ### detectedAtStartup [Section titled “detectedAtStartup”](#detectedatstartup) > **detectedAtStartup**: `boolean` Defined in: [packages/client/src/results.ts:227](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L227) *** ### emojiCount [Section titled “emojiCount”](#emojicount) > **emojiCount**: `number` | `null` Defined in: [packages/client/src/results.ts:223](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L223) *** ### features [Section titled “features”](#features) > **features**: `string`\[] Defined in: [packages/client/src/results.ts:210](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L210) *** ### firstCommandAt [Section titled “firstCommandAt”](#firstcommandat) > **firstCommandAt**: `string` | `null` Defined in: [packages/client/src/results.ts:229](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L229) *** ### icon [Section titled “icon”](#icon) > **icon**: `string` | `null` Defined in: [packages/client/src/results.ts:205](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L205) *** ### id [Section titled “id”](#id) > **id**: `string` Defined in: [packages/client/src/results.ts:202](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L202) *** ### joinedAt [Section titled “joinedAt”](#joinedat) > **joinedAt**: `string` Defined in: [packages/client/src/results.ts:217](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L217) *** ### large [Section titled “large”](#large) > **large**: `boolean` | `null` Defined in: [packages/client/src/results.ts:208](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L208) *** ### lastCommandAt [Section titled “lastCommandAt”](#lastcommandat) > **lastCommandAt**: `string` | `null` Defined in: [packages/client/src/results.ts:230](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L230) *** ### leftAt [Section titled “leftAt”](#leftat) > **leftAt**: `string` | `null` Defined in: [packages/client/src/results.ts:218](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L218) *** ### locale [Section titled “locale”](#locale) > **locale**: `string` | `null` Defined in: [packages/client/src/results.ts:209](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L209) *** ### memberCount [Section titled “memberCount”](#membercount) > **memberCount**: `number` Defined in: [packages/client/src/results.ts:206](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L206) *** ### mfaLevel [Section titled “mfaLevel”](#mfalevel) > **mfaLevel**: `number` | `null` Defined in: [packages/client/src/results.ts:215](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L215) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/results.ts:204](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L204) Text chosen by the server’s owner: render it as text. *** ### nsfwLevel [Section titled “nsfwLevel”](#nsfwlevel) > **nsfwLevel**: `number` | `null` Defined in: [packages/client/src/results.ts:214](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L214) *** ### premiumTier [Section titled “premiumTier”](#premiumtier) > **premiumTier**: `number` | `null` Defined in: [packages/client/src/results.ts:211](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L211) *** ### roleCount [Section titled “roleCount”](#rolecount) > **roleCount**: `number` | `null` Defined in: [packages/client/src/results.ts:222](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L222) *** ### shard [Section titled “shard”](#shard) > **shard**: `number` | `null` Defined in: [packages/client/src/results.ts:219](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L219) *** ### sizeAtJoin [Section titled “sizeAtJoin”](#sizeatjoin) > **sizeAtJoin**: `number` | `null` Defined in: [packages/client/src/results.ts:207](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L207) *** ### stickerCount [Section titled “stickerCount”](#stickercount) > **stickerCount**: `number` | `null` Defined in: [packages/client/src/results.ts:224](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L224) *** ### updatedAt [Section titled “updatedAt”](#updatedat) > **updatedAt**: `string` Defined in: [packages/client/src/results.ts:231](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L231) *** ### verificationLevel [Section titled “verificationLevel”](#verificationlevel) > **verificationLevel**: `number` | `null` Defined in: [packages/client/src/results.ts:213](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L213) # ServerQuery Defined in: [packages/client/src/specs.ts:152](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L152) One server’s profile and history. ## Properties [Section titled “Properties”](#properties) ### guild [Section titled “guild”](#guild) > **guild**: `string` Defined in: [packages/client/src/specs.ts:155](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L155) The server’s ID. *** ### kind [Section titled “kind”](#kind) > **kind**: `"server"` Defined in: [packages/client/src/specs.ts:153](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L153) # ServerRow Defined in: [packages/client/src/results.ts:169](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L169) One server in the answer to a `servers` query. ## Properties [Section titled “Properties”](#properties) ### baseline [Section titled “baseline”](#baseline) > **baseline**: `boolean` Defined in: [packages/client/src/results.ts:188](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L188) The bot was already in the server when Shardlens was installed. *** ### boosts [Section titled “boosts”](#boosts) > **boosts**: `number` | `null` Defined in: [packages/client/src/results.ts:176](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L176) *** ### detectedAtStartup [Section titled “detectedAtStartup”](#detectedatstartup) > **detectedAtStartup**: `boolean` Defined in: [packages/client/src/results.ts:186](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L186) The bot joined while it was offline, so `joinedAt` is when it noticed. *** ### features [Section titled “features”](#features) > **features**: `string`\[] Defined in: [packages/client/src/results.ts:179](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L179) *** ### icon [Section titled “icon”](#icon) > **icon**: `string` | `null` Defined in: [packages/client/src/results.ts:174](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L174) Discord’s icon hash. *** ### id [Section titled “id”](#id) > **id**: `string` Defined in: [packages/client/src/results.ts:170](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L170) *** ### joinedAt [Section titled “joinedAt”](#joinedat) > **joinedAt**: `string` Defined in: [packages/client/src/results.ts:180](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L180) *** ### lastActive [Section titled “lastActive”](#lastactive) > **lastActive**: `string` | `null` Defined in: [packages/client/src/results.ts:184](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L184) The last command run in the server. *** ### leftAt [Section titled “leftAt”](#leftat) > **leftAt**: `string` | `null` Defined in: [packages/client/src/results.ts:181](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L181) *** ### locale [Section titled “locale”](#locale) > **locale**: `string` | `null` Defined in: [packages/client/src/results.ts:178](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L178) *** ### memberCount [Section titled “memberCount”](#membercount) > **memberCount**: `number` Defined in: [packages/client/src/results.ts:175](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L175) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/client/src/results.ts:172](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L172) Text chosen by the server’s owner: render it as text. *** ### premiumTier [Section titled “premiumTier”](#premiumtier) > **premiumTier**: `number` | `null` Defined in: [packages/client/src/results.ts:177](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L177) *** ### runs [Section titled “runs”](#runs) > **runs**: `number` Defined in: [packages/client/src/results.ts:190](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L190) Command runs in the last 30 days. *** ### shard [Section titled “shard”](#shard) > **shard**: `number` | `null` Defined in: [packages/client/src/results.ts:182](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L182) # ServersQuery Defined in: [packages/client/src/specs.ts:125](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L125) The servers the bot is or was in, one page at a time. ## Properties [Section titled “Properties”](#properties) ### feature? [Section titled “feature?”](#feature) > `optional` **feature?**: `string` Defined in: [packages/client/src/specs.ts:132](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L132) A Discord server feature, such as `COMMUNITY`. *** ### inactive? [Section titled “inactive?”](#inactive) > `optional` **inactive?**: `boolean` Defined in: [packages/client/src/specs.ts:138](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L138) Only servers with no command in the last 30 days. *** ### kind [Section titled “kind”](#kind) > **kind**: `"servers"` Defined in: [packages/client/src/specs.ts:126](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L126) *** ### limit? [Section titled “limit?”](#limit) > `optional` **limit?**: `number` Defined in: [packages/client/src/specs.ts:146](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L146) 1 to 200, default 50. *** ### locale? [Section titled “locale?”](#locale) > `optional` **locale?**: `string` Defined in: [packages/client/src/specs.ts:134](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L134) The server’s preferred locale, such as `en-GB`. *** ### missingPermissions? [Section titled “missingPermissions?”](#missingpermissions) > `optional` **missingPermissions?**: `boolean` Defined in: [packages/client/src/specs.ts:140](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L140) Only servers where the bot lacks a permission that Settings lists as required. *** ### offset? [Section titled “offset?”](#offset) > `optional` **offset?**: `number` Defined in: [packages/client/src/specs.ts:148](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L148) Rows to skip. Default 0. *** ### order? [Section titled “order?”](#order) > `optional` **order?**: `"asc"` | `"desc"` Defined in: [packages/client/src/specs.ts:144](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L144) Default `'desc'`. *** ### search? [Section titled “search?”](#search) > `optional` **search?**: `string` Defined in: [packages/client/src/specs.ts:128](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L128) Part of a server’s name. *** ### size? [Section titled “size?”](#size) > `optional` **size?**: `"1-10"` | `"11-100"` | `"101-1k"` | `"1k-10k"` | `"10k+"` Defined in: [packages/client/src/specs.ts:136](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L136) Member count. *** ### sort? [Section titled “sort?”](#sort) > `optional` **sort?**: `"joined"` | `"name"` | `"members"` | `"last_active"` | `"runs"` Defined in: [packages/client/src/specs.ts:142](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L142) Default `'members'`. *** ### status? [Section titled “status?”](#status) > `optional` **status?**: `"active"` | `"left"` | `"all"` Defined in: [packages/client/src/specs.ts:130](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L130) Default `'active'`: servers the bot is in now. # ServersResult Defined in: [packages/client/src/results.ts:194](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L194) Answer to a `servers` query. ## Properties [Section titled “Properties”](#properties) ### rows [Section titled “rows”](#rows) > **rows**: [`ServerRow`](/Shardlens/reference/sdk/shardlens/client/interfaces/serverrow/)\[] Defined in: [packages/client/src/results.ts:197](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L197) *** ### total [Section titled “total”](#total) > **total**: `number` Defined in: [packages/client/src/results.ts:196](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L196) Servers matching the filters, on every page. # ShardlensActivity Defined in: [packages/client/src/client.ts:55](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L55) Who ran what, from a collector in audit mode. Needs an activity key (`slk_activity_…`): with a read key these reject with `activity_key_required`, and with `audit_mode_off` when the collector hashes users instead. ## Methods [Section titled “Methods”](#methods) ### log() [Section titled “log()”](#log) > **log**(`filters?`, `options?`): `Promise`<[`ActivityLogPage`](/Shardlens/reference/sdk/shardlens/client/interfaces/activitylogpage/)> Defined in: [packages/client/src/client.ts:57](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L57) One page of the activity log, newest first. Pass a page’s `nextBefore` as `before` for the page after it. #### Parameters [Section titled “Parameters”](#parameters) ##### filters? [Section titled “filters?”](#filters) [`ActivityLogFilters`](/Shardlens/reference/sdk/shardlens/client/interfaces/activitylogfilters/) ##### options? [Section titled “options?”](#options) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns) `Promise`<[`ActivityLogPage`](/Shardlens/reference/sdk/shardlens/client/interfaces/activitylogpage/)> *** ### topUsers() [Section titled “topUsers()”](#topusers) > **topUsers**(`window?`, `options?`): `Promise`<[`ActivityTopUsers`](/Shardlens/reference/sdk/shardlens/client/interfaces/activitytopusers/)> Defined in: [packages/client/src/client.ts:59](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L59) The users who ran the most in the last 24 hours (the default) or 7 days. #### Parameters [Section titled “Parameters”](#parameters-1) ##### window? [Section titled “window?”](#window) `"24h"` | `"7d"` ##### options? [Section titled “options?”](#options-1) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-1) `Promise`<[`ActivityTopUsers`](/Shardlens/reference/sdk/shardlens/client/interfaces/activitytopusers/)> # ShardlensClient Defined in: [packages/client/src/client.ts:63](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L63) Reads one collector. Every method rejects with a [ShardlensClientError](/Shardlens/reference/sdk/shardlens/client/classes/shardlensclienterror/) when it can’t get an answer. ## Properties [Section titled “Properties”](#properties) ### activity [Section titled “activity”](#activity) > `readonly` **activity**: [`ShardlensActivity`](/Shardlens/reference/sdk/shardlens/client/interfaces/shardlensactivity/) Defined in: [packages/client/src/client.ts:121](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L121) Who ran what: the activity log of a collector in audit mode. ## Methods [Section titled “Methods”](#methods) ### audience() [Section titled “audience()”](#audience) > **audience**(`spec`, `options?`): `Promise`<[`AudienceResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/audienceresult/)> Defined in: [packages/client/src/client.ts:85](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L85) Unique users per day, week and salt period, and how runs split by locale, install, context and member tier. #### Parameters [Section titled “Parameters”](#parameters) ##### spec [Section titled “spec”](#spec) `Omit`<[`AudienceQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/audiencequery/), `"kind"`> ##### options? [Section titled “options?”](#options) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns) `Promise`<[`AudienceResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/audienceresult/)> *** ### bursts() [Section titled “bursts()”](#bursts) > **bursts**(`spec`, `options?`): `Promise`<[`BurstsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/burstsresult/)> Defined in: [packages/client/src/client.ts:91](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L91) Minutes with far more runs than the median minute. #### Parameters [Section titled “Parameters”](#parameters-1) ##### spec [Section titled “spec”](#spec-1) `Omit`<[`BurstsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/burstsquery/), `"kind"`> ##### options? [Section titled “options?”](#options-1) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-1) `Promise`<[`BurstsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/burstsresult/)> *** ### command() [Section titled “command()”](#command) > **command**(`name`, `spec`, `options?`): `Promise`<[`CommandResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandresult/)> Defined in: [packages/client/src/client.ts:71](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L71) One command in depth: outcomes, subcommands, options, where and by whom it runs. #### Parameters [Section titled “Parameters”](#parameters-2) ##### name [Section titled “name”](#name) `string` ##### spec [Section titled “spec”](#spec-2) `Omit`<[`CommandQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandquery/), `"kind"` | `"name"`> ##### options? [Section titled “options?”](#options-2) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-2) `Promise`<[`CommandResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandresult/)> *** ### commands() [Section titled “commands()”](#commands) > **commands**(`spec`, `options?`): `Promise`<[`CommandsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandsresult/)> Defined in: [packages/client/src/client.ts:69](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L69) Every command that ran or is registered, compared with the period before. #### Parameters [Section titled “Parameters”](#parameters-3) ##### spec [Section titled “spec”](#spec-3) `Omit`<[`CommandsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandsquery/), `"kind"`> ##### options? [Section titled “options?”](#options-3) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-3) `Promise`<[`CommandsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandsresult/)> *** ### eventProps() [Section titled “eventProps()”](#eventprops) #### Call Signature [Section titled “Call Signature”](#call-signature) > **eventProps**(`spec`, `options?`): `Promise`<[`EventPropValues`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropvalues/)> Defined in: [packages/client/src/client.ts:99](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L99) One custom event’s property names or, with `prop`, the most common values of that property. ##### Parameters [Section titled “Parameters”](#parameters-4) ###### spec [Section titled “spec”](#spec-4) `Omit`<[`EventPropsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropsquery/), `"kind"` | `"prop"`> & `object` ###### options? [Section titled “options?”](#options-4) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) ##### Returns [Section titled “Returns”](#returns-4) `Promise`<[`EventPropValues`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropvalues/)> #### Call Signature [Section titled “Call Signature”](#call-signature-1) > **eventProps**(`spec`, `options?`): `Promise`<[`EventPropKeys`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropkeys/)> Defined in: [packages/client/src/client.ts:103](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L103) ##### Parameters [Section titled “Parameters”](#parameters-5) ###### spec [Section titled “spec”](#spec-5) `Omit`<[`EventPropsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropsquery/), `"kind"` | `"prop"`> & `object` ###### options? [Section titled “options?”](#options-5) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) ##### Returns [Section titled “Returns”](#returns-5) `Promise`<[`EventPropKeys`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropkeys/)> #### Call Signature [Section titled “Call Signature”](#call-signature-2) > **eventProps**(`spec`, `options?`): `Promise`<[`EventPropsResult`](/Shardlens/reference/sdk/shardlens/client/type-aliases/eventpropsresult/)> Defined in: [packages/client/src/client.ts:107](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L107) ##### Parameters [Section titled “Parameters”](#parameters-6) ###### spec [Section titled “spec”](#spec-6) `Omit`<[`EventPropsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropsquery/), `"kind"`> ###### options? [Section titled “options?”](#options-6) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) ##### Returns [Section titled “Returns”](#returns-6) `Promise`<[`EventPropsResult`](/Shardlens/reference/sdk/shardlens/client/type-aliases/eventpropsresult/)> *** ### events() [Section titled “events()”](#events) > **events**(`spec`, `options?`): `Promise`<[`EventsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventsresult/)> Defined in: [packages/client/src/client.ts:97](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L97) The custom events sent with `track()`. #### Parameters [Section titled “Parameters”](#parameters-7) ##### spec [Section titled “spec”](#spec-7) `Omit`<[`EventsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventsquery/), `"kind"`> ##### options? [Section titled “options?”](#options-7) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-7) `Promise`<[`EventsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventsresult/)> *** ### funnel() [Section titled “funnel()”](#funnel) > **funnel**(`spec`, `options?`): `Promise`<[`FunnelResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/funnelresult/)> Defined in: [packages/client/src/client.ts:109](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L109) How many people got through 2 to 5 steps (custom events or commands), in order. #### Parameters [Section titled “Parameters”](#parameters-8) ##### spec [Section titled “spec”](#spec-8) `Omit`<[`FunnelQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/funnelquery/), `"kind"`> ##### options? [Section titled “options?”](#options-8) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-8) `Promise`<[`FunnelResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/funnelresult/)> *** ### gauge() [Section titled “gauge()”](#gauge) > **gauge**(`spec`, `options?`): `Promise`<[`GaugeResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/gaugeresult/)> Defined in: [packages/client/src/client.ts:89](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L89) A gauge over time, such as `shard.ping_ms` or `memory.rss_bytes`. #### Parameters [Section titled “Parameters”](#parameters-9) ##### spec [Section titled “spec”](#spec-9) `Omit`<[`GaugeQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/gaugequery/), `"kind"`> ##### options? [Section titled “options?”](#options-9) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-9) `Promise`<[`GaugeResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/gaugeresult/)> *** ### growth() [Section titled “growth()”](#growth) > **growth**(`spec`, `options?`): `Promise`<[`GrowthResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/growthresult/)> Defined in: [packages/client/src/client.ts:83](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L83) Servers joined and left, activation, cohorts and how long servers stay. #### Parameters [Section titled “Parameters”](#parameters-10) ##### spec [Section titled “spec”](#spec-10) `Omit`<[`GrowthQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/growthquery/), `"kind"`> ##### options? [Section titled “options?”](#options-10) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-10) `Promise`<[`GrowthResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/growthresult/)> *** ### heatmap() [Section titled “heatmap()”](#heatmap) > **heatmap**(`spec`, `options?`): `Promise`<[`HeatmapResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/heatmapresult/)> Defined in: [packages/client/src/client.ts:77](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L77) Counts by weekday and hour of the day. #### Parameters [Section titled “Parameters”](#parameters-11) ##### spec [Section titled “spec”](#spec-11) `Omit`<[`HeatmapQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/heatmapquery/), `"kind"`> ##### options? [Section titled “options?”](#options-11) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-11) `Promise`<[`HeatmapResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/heatmapresult/)> *** ### installs() [Section titled “installs()”](#installs) > **installs**(`spec`, `options?`): `Promise`<[`InstallsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/installsresult/)> Defined in: [packages/client/src/client.ts:95](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L95) User installs and removals, from Discord’s webhook events. #### Parameters [Section titled “Parameters”](#parameters-12) ##### spec [Section titled “spec”](#spec-12) `Omit`<[`InstallsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/installsquery/), `"kind"`> ##### options? [Section titled “options?”](#options-12) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-12) `Promise`<[`InstallsResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/installsresult/)> *** ### live() [Section titled “live()”](#live) > **live**(`options?`): `AsyncIterable`<[`LiveUpdate`](/Shardlens/reference/sdk/shardlens/client/interfaces/liveupdate/)> Defined in: [packages/client/src/client.ts:119](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L119) What the bot is doing right now, about once a second, over Server-Sent Events. The connection opens when iteration starts and is closed when it ends: on the signal, on leaving the loop, or when the collector closes the stream (a restart, a proxy’s time limit). Call `live()` again to reconnect. #### Parameters [Section titled “Parameters”](#parameters-13) ##### options? [Section titled “options?”](#options-13) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-13) `AsyncIterable`<[`LiveUpdate`](/Shardlens/reference/sdk/shardlens/client/interfaces/liveupdate/)> *** ### meta() [Section titled “meta()”](#meta) > **meta**(`options?`): `Promise`<[`Meta`](/Shardlens/reference/sdk/shardlens/client/interfaces/meta/)> Defined in: [packages/client/src/client.ts:113](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L113) The app and how its collector is set up: mode, salt period, time zone, retention. #### Parameters [Section titled “Parameters”](#parameters-14) ##### options? [Section titled “options?”](#options-14) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-14) `Promise`<[`Meta`](/Shardlens/reference/sdk/shardlens/client/interfaces/meta/)> *** ### overview() [Section titled “overview()”](#overview) > **overview**(`options?`): `Promise`<[`OverviewResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/overviewresult/)> Defined in: [packages/client/src/client.ts:67](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L67) The bot at a glance: the last 30 days of runs, servers, users, and whether events are arriving. #### Parameters [Section titled “Parameters”](#parameters-15) ##### options? [Section titled “options?”](#options-15) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-15) `Promise`<[`OverviewResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/overviewresult/)> *** ### premium() [Section titled “premium()”](#premium) > **premium**(`spec`, `options?`): `Promise`<[`PremiumResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/premiumresult/)> Defined in: [packages/client/src/client.ts:93](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L93) Entitlements and subscriptions by SKU, and the premium share of runs. #### Parameters [Section titled “Parameters”](#parameters-16) ##### spec [Section titled “spec”](#spec-13) `Omit`<[`PremiumQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/premiumquery/), `"kind"`> ##### options? [Section titled “options?”](#options-16) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-16) `Promise`<[`PremiumResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/premiumresult/)> *** ### query() [Section titled “query()”](#query) > **query**<`S`>(`spec`, `options?`): `Promise`<[`QueryResults`](/Shardlens/reference/sdk/shardlens/client/interfaces/queryresults/)\[`S`\[`"kind"`]]> Defined in: [packages/client/src/client.ts:65](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L65) Runs any query. The answer’s type follows the spec’s `kind`. #### Type Parameters [Section titled “Type Parameters”](#type-parameters) ##### S [Section titled “S”](#s) `S` *extends* [`QuerySpec`](/Shardlens/reference/sdk/shardlens/client/type-aliases/queryspec/) #### Parameters [Section titled “Parameters”](#parameters-17) ##### spec [Section titled “spec”](#spec-14) `S` ##### options? [Section titled “options?”](#options-17) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-17) `Promise`<[`QueryResults`](/Shardlens/reference/sdk/shardlens/client/interfaces/queryresults/)\[`S`\[`"kind"`]]> *** ### reliability() [Section titled “reliability()”](#reliability) > **reliability**(`spec`, `options?`): `Promise`<[`ReliabilityResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/reliabilityresult/)> Defined in: [packages/client/src/client.ts:87](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L87) Missed deadlines, errors, REST calls, rate limits, shards and the SDK’s own health. #### Parameters [Section titled “Parameters”](#parameters-18) ##### spec [Section titled “spec”](#spec-15) `Omit`<[`ReliabilityQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/reliabilityquery/), `"kind"`> ##### options? [Section titled “options?”](#options-18) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-18) `Promise`<[`ReliabilityResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/reliabilityresult/)> *** ### retention() [Section titled “retention()”](#retention) > **retention**(`spec`, `options?`): `Promise`<[`RetentionResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/retentionresult/)> Defined in: [packages/client/src/client.ts:111](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L111) People who did one thing, by when they first did, and how many came back in each later period. #### Parameters [Section titled “Parameters”](#parameters-19) ##### spec [Section titled “spec”](#spec-16) `Omit`<[`RetentionQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/retentionquery/), `"kind"`> ##### options? [Section titled “options?”](#options-19) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-19) `Promise`<[`RetentionResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/retentionresult/)> *** ### series() [Section titled “series()”](#series) > **series**(`spec`, `options?`): `Promise`<[`SeriesResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/seriesresult/)> Defined in: [packages/client/src/client.ts:73](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L73) A metric over time, optionally split by one dimension. #### Parameters [Section titled “Parameters”](#parameters-20) ##### spec [Section titled “spec”](#spec-17) `Omit`<[`SeriesQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/seriesquery/), `"kind"`> ##### options? [Section titled “options?”](#options-20) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-20) `Promise`<[`SeriesResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/seriesresult/)> *** ### server() [Section titled “server()”](#server) > **server**(`guild`, `options?`): `Promise`<[`ServerResult`](/Shardlens/reference/sdk/shardlens/client/type-aliases/serverresult/)> Defined in: [packages/client/src/client.ts:81](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L81) One server’s profile and history. `found` is `false` for a server the collector has never seen. #### Parameters [Section titled “Parameters”](#parameters-21) ##### guild [Section titled “guild”](#guild) `string` ##### options? [Section titled “options?”](#options-21) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-21) `Promise`<[`ServerResult`](/Shardlens/reference/sdk/shardlens/client/type-aliases/serverresult/)> *** ### servers() [Section titled “servers()”](#servers) > **servers**(`spec?`, `options?`): `Promise`<[`ServersResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/serversresult/)> Defined in: [packages/client/src/client.ts:79](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L79) The servers the bot is or was in, filtered and sorted, one page at a time. #### Parameters [Section titled “Parameters”](#parameters-22) ##### spec? [Section titled “spec?”](#spec-18) `Omit`<[`ServersQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/serversquery/), `"kind"`> ##### options? [Section titled “options?”](#options-22) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-22) `Promise`<[`ServersResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/serversresult/)> *** ### top() [Section titled “top()”](#top) > **top**(`spec`, `options?`): `Promise`<[`TopResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/topresult/)> Defined in: [packages/client/src/client.ts:75](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/client.ts#L75) The busiest values of one dimension: top commands, top servers, top routes. #### Parameters [Section titled “Parameters”](#parameters-23) ##### spec [Section titled “spec”](#spec-19) `Omit`<[`TopQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/topquery/), `"kind"`> ##### options? [Section titled “options?”](#options-23) [`RequestOptions`](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) #### Returns [Section titled “Returns”](#returns-23) `Promise`<[`TopResult`](/Shardlens/reference/sdk/shardlens/client/interfaces/topresult/)> # ShardlensClientOptions Defined in: [packages/client/src/transport.ts:4](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/transport.ts#L4) Options of [createShardlensClient](/Shardlens/reference/sdk/shardlens/client/functions/createshardlensclient/). ## Properties [Section titled “Properties”](#properties) ### apiKey [Section titled “apiKey”](#apikey) > **apiKey**: `string` Defined in: [packages/client/src/transport.ts:14](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/transport.ts#L14) A read key (`slk_read_…`) or, to read the activity log as well, an activity key (`slk_activity_…`). Keep it on your server: a key in a browser can be read by every visitor. *** ### endpoint [Section titled “endpoint”](#endpoint) > **endpoint**: `string` Defined in: [packages/client/src/transport.ts:9](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/transport.ts#L9) Your collector’s address, such as `https://stats.example.com`: the SDK’s `endpoint` (`SHARDLENS_URL`). HTTPS, or HTTP to localhost only, and no path. *** ### fetch? [Section titled “fetch?”](#fetch) > `optional` **fetch?**: {(`input`, `init?`): `Promise`<`Response`>; (`input`, `init?`): `Promise`<`Response`>; } Defined in: [packages/client/src/transport.ts:18](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/transport.ts#L18) The `fetch` to send requests with. Default: the global one. #### Call Signature [Section titled “Call Signature”](#call-signature) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters) ###### input [Section titled “input”](#input) `URL` | `RequestInfo` ###### init? [Section titled “init?”](#init) `RequestInit` ##### Returns [Section titled “Returns”](#returns) `Promise`<`Response`> #### Call Signature [Section titled “Call Signature”](#call-signature-1) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters-1) ###### input [Section titled “input”](#input-1) `string` | `URL` | `Request` ###### init? [Section titled “init?”](#init-1) `RequestInit` ##### Returns [Section titled “Returns”](#returns-1) `Promise`<`Response`> *** ### timeoutMs? [Section titled “timeoutMs?”](#timeoutms) > `optional` **timeoutMs?**: `number` Defined in: [packages/client/src/transport.ts:16](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/transport.ts#L16) How long a request may take, and how long a live stream may take to connect, in milliseconds. Default 10,000. # TimeRange Defined in: [packages/client/src/specs.ts:5](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L5) A time span. Both ends are ISO 8601 date-times with an offset (`2026-11-01T00:00:00Z`), `from` before `to`, at most 400 days apart. [lastDays](/Shardlens/reference/sdk/shardlens/client/functions/lastdays/) makes one. ## Properties [Section titled “Properties”](#properties) ### from [Section titled “from”](#from) > **from**: `string` Defined in: [packages/client/src/specs.ts:6](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L6) *** ### to [Section titled “to”](#to) > **to**: `string` Defined in: [packages/client/src/specs.ts:7](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L7) # TopQuery Defined in: [packages/client/src/specs.ts:84](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L84) The busiest values of one dimension. ## Properties [Section titled “Properties”](#properties) ### filters? [Section titled “filters?”](#filters) > `optional` **filters?**: readonly [`Filter`](/Shardlens/reference/sdk/shardlens/client/interfaces/filter/)\[] Defined in: [packages/client/src/specs.ts:93](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L93) Up to 10. *** ### groupBy [Section titled “groupBy”](#groupby) > **groupBy**: [`Dimension`](/Shardlens/reference/sdk/shardlens/client/type-aliases/dimension/) Defined in: [packages/client/src/specs.ts:90](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L90) *** ### kind [Section titled “kind”](#kind) > **kind**: `"top"` Defined in: [packages/client/src/specs.ts:85](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L85) *** ### limit? [Section titled “limit?”](#limit) > `optional` **limit?**: `number` Defined in: [packages/client/src/specs.ts:95](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L95) 1 to 500, default 20. *** ### metric [Section titled “metric”](#metric) > **metric**: [`SeriesMetric`](/Shardlens/reference/sdk/shardlens/client/type-aliases/seriesmetric/) Defined in: [packages/client/src/specs.ts:86](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L86) *** ### name? [Section titled “name?”](#name) > `optional` **name?**: `string` Defined in: [packages/client/src/specs.ts:88](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L88) For `metric: 'custom'`: the event’s name. *** ### range [Section titled “range”](#range) > **range**: [`TimeRange`](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) Defined in: [packages/client/src/specs.ts:89](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L89) *** ### stat? [Section titled “stat?”](#stat) > `optional` **stat?**: [`Stat`](/Shardlens/reference/sdk/shardlens/client/type-aliases/stat/) Defined in: [packages/client/src/specs.ts:91](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L91) # TopResult Defined in: [packages/client/src/results.ts:52](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L52) Answer to a `top` query. ## Properties [Section titled “Properties”](#properties) ### rows [Section titled “rows”](#rows) > **rows**: `object`\[] Defined in: [packages/client/src/results.ts:53](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L53) #### count [Section titled “count”](#count) > **count**: `number` How many events the row covers, whatever the `stat`. #### icon? [Section titled “icon?”](#icon) > `optional` **icon?**: `string` | `null` With `groupBy: 'guild'` only: the server’s icon hash. #### key [Section titled “key”](#key) > **key**: `string` The `groupBy` value; `''` for events without it. #### name? [Section titled “name?”](#name) > `optional` **name?**: `string` | `null` With `groupBy: 'guild'` only: the server’s name, `null` when the collector has no profile for it. #### value [Section titled “value”](#value) > **value**: `number` | `null` The asked `stat`. # @shardlens/client `@shardlens/client`: a typed client for reading a Shardlens collector from your own dashboard or scripts. Every query the built-in dashboard runs, the live stream and, with an activity key, the activity log. Zero dependencies and Web-standard APIs only, so it runs on Node, Bun, Deno, Cloudflare Workers and in Next.js route handlers. ## Classes [Section titled “Classes”](#classes) * [ShardlensClientError](/Shardlens/reference/sdk/shardlens/client/classes/shardlensclienterror/) ## Interfaces [Section titled “Interfaces”](#interfaces) * [ActivityLogFilters](/Shardlens/reference/sdk/shardlens/client/interfaces/activitylogfilters/) * [ActivityLogPage](/Shardlens/reference/sdk/shardlens/client/interfaces/activitylogpage/) * [ActivityRow](/Shardlens/reference/sdk/shardlens/client/interfaces/activityrow/) * [ActivityTopUsers](/Shardlens/reference/sdk/shardlens/client/interfaces/activitytopusers/) * [AudienceQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/audiencequery/) * [AudienceResult](/Shardlens/reference/sdk/shardlens/client/interfaces/audienceresult/) * [BurstsQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/burstsquery/) * [BurstsResult](/Shardlens/reference/sdk/shardlens/client/interfaces/burstsresult/) * [CommandQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/commandquery/) * [CommandResult](/Shardlens/reference/sdk/shardlens/client/interfaces/commandresult/) * [CommandRow](/Shardlens/reference/sdk/shardlens/client/interfaces/commandrow/) * [CommandsQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/commandsquery/) * [CommandsResult](/Shardlens/reference/sdk/shardlens/client/interfaces/commandsresult/) * [EventPropKeys](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropkeys/) * [EventPropsQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropsquery/) * [EventPropValues](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropvalues/) * [EventsQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/eventsquery/) * [EventsResult](/Shardlens/reference/sdk/shardlens/client/interfaces/eventsresult/) * [Filter](/Shardlens/reference/sdk/shardlens/client/interfaces/filter/) * [FunnelQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/funnelquery/) * [FunnelResult](/Shardlens/reference/sdk/shardlens/client/interfaces/funnelresult/) * [GaugeQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/gaugequery/) * [GaugeResult](/Shardlens/reference/sdk/shardlens/client/interfaces/gaugeresult/) * [GrowthQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/growthquery/) * [GrowthResult](/Shardlens/reference/sdk/shardlens/client/interfaces/growthresult/) * [HeatmapQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/heatmapquery/) * [HeatmapResult](/Shardlens/reference/sdk/shardlens/client/interfaces/heatmapresult/) * [InstallsQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/installsquery/) * [InstallsResult](/Shardlens/reference/sdk/shardlens/client/interfaces/installsresult/) * [KeyCount](/Shardlens/reference/sdk/shardlens/client/interfaces/keycount/) * [LiveUpdate](/Shardlens/reference/sdk/shardlens/client/interfaces/liveupdate/) * [Meta](/Shardlens/reference/sdk/shardlens/client/interfaces/meta/) * [NullableKeyCount](/Shardlens/reference/sdk/shardlens/client/interfaces/nullablekeycount/) * [OverviewQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/overviewquery/) * [OverviewResult](/Shardlens/reference/sdk/shardlens/client/interfaces/overviewresult/) * [PremiumQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/premiumquery/) * [PremiumResult](/Shardlens/reference/sdk/shardlens/client/interfaces/premiumresult/) * [QueryResults](/Shardlens/reference/sdk/shardlens/client/interfaces/queryresults/) * [ReliabilityQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/reliabilityquery/) * [ReliabilityResult](/Shardlens/reference/sdk/shardlens/client/interfaces/reliabilityresult/) * [RequestOptions](/Shardlens/reference/sdk/shardlens/client/interfaces/requestoptions/) * [RetentionQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/retentionquery/) * [RetentionResult](/Shardlens/reference/sdk/shardlens/client/interfaces/retentionresult/) * [SdkInstance](/Shardlens/reference/sdk/shardlens/client/interfaces/sdkinstance/) * [SeriesQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/seriesquery/) * [SeriesResult](/Shardlens/reference/sdk/shardlens/client/interfaces/seriesresult/) * [ServerProfile](/Shardlens/reference/sdk/shardlens/client/interfaces/serverprofile/) * [ServerQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/serverquery/) * [ServerRow](/Shardlens/reference/sdk/shardlens/client/interfaces/serverrow/) * [ServersQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/serversquery/) * [ServersResult](/Shardlens/reference/sdk/shardlens/client/interfaces/serversresult/) * [ShardlensActivity](/Shardlens/reference/sdk/shardlens/client/interfaces/shardlensactivity/) * [ShardlensClient](/Shardlens/reference/sdk/shardlens/client/interfaces/shardlensclient/) * [ShardlensClientOptions](/Shardlens/reference/sdk/shardlens/client/interfaces/shardlensclientoptions/) * [TimeRange](/Shardlens/reference/sdk/shardlens/client/interfaces/timerange/) * [TopQuery](/Shardlens/reference/sdk/shardlens/client/interfaces/topquery/) * [TopResult](/Shardlens/reference/sdk/shardlens/client/interfaces/topresult/) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [ActivityOutcome](/Shardlens/reference/sdk/shardlens/client/type-aliases/activityoutcome/) * [Dimension](/Shardlens/reference/sdk/shardlens/client/type-aliases/dimension/) * [EventPropsResult](/Shardlens/reference/sdk/shardlens/client/type-aliases/eventpropsresult/) * [QuerySpec](/Shardlens/reference/sdk/shardlens/client/type-aliases/queryspec/) * [SeriesMetric](/Shardlens/reference/sdk/shardlens/client/type-aliases/seriesmetric/) * [ServerResult](/Shardlens/reference/sdk/shardlens/client/type-aliases/serverresult/) * [Stat](/Shardlens/reference/sdk/shardlens/client/type-aliases/stat/) * [Step](/Shardlens/reference/sdk/shardlens/client/type-aliases/step/) ## Functions [Section titled “Functions”](#functions) * [createShardlensClient](/Shardlens/reference/sdk/shardlens/client/functions/createshardlensclient/) * [lastDays](/Shardlens/reference/sdk/shardlens/client/functions/lastdays/) # ActivityOutcome > **ActivityOutcome** = `"ok"` | `"error"` | `"timeout"` | `"no_response"` Defined in: [packages/client/src/activity.ts:2](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/activity.ts#L2) How an interaction ended. `timeout`: the first response missed Discord’s 3-second deadline. # Dimension > **Dimension** = `"command"` | `"sub"` | `"kind"` | `"outcome"` | `"context"` | `"install"` | `"guild"` | `"locale"` | `"tier"` | `"custom_id"` | `"source"` | `"option"` | `"error_class"` | `"method"` | `"route"` | `"status"` | `"scope"` | `"detected"` Defined in: [packages/client/src/specs.ts:30](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L30) What a query can group or filter by. Each metric keeps only some of these, and the collector answers `invalid_query`, naming the ones it keeps, when asked for another. There is no user dimension. # EventPropsResult > **EventPropsResult** = [`EventPropKeys`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropkeys/) | [`EventPropValues`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropvalues/) Defined in: [packages/client/src/results.ts:463](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L463) Answer to an `eventProps` query. # QuerySpec > **QuerySpec** = [`SeriesQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/seriesquery/) | [`TopQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/topquery/) | [`HeatmapQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/heatmapquery/) | [`CommandsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandsquery/) | [`CommandQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/commandquery/) | [`ServersQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/serversquery/) | [`ServerQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/serverquery/) | [`GrowthQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/growthquery/) | [`AudienceQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/audiencequery/) | [`OverviewQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/overviewquery/) | [`GaugeQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/gaugequery/) | [`BurstsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/burstsquery/) | [`ReliabilityQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/reliabilityquery/) | [`PremiumQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/premiumquery/) | [`InstallsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/installsquery/) | [`EventsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventsquery/) | [`EventPropsQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/eventpropsquery/) | [`FunnelQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/funnelquery/) | [`RetentionQuery`](/Shardlens/reference/sdk/shardlens/client/interfaces/retentionquery/) Defined in: [packages/client/src/specs.ts:258](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L258) Any query the collector’s `POST /v1/query` accepts, told apart by `kind`. # SeriesMetric > **SeriesMetric** = `"interactions"` | `"interactions.autocomplete"` | `"components"` | `"modals.submitted"` | `"modals.shown"` | `"interactions.errors"` | `"rest.calls"` | `"rest.invalid"` | `"rest.ratelimits"` | `"guild.joins"` | `"guild.leaves"` | `"guild.unavailable"` | `"custom"` Defined in: [packages/client/src/specs.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L11) What a `series`, `top` or `heatmap` query counts. `custom` is a custom event, named by the query’s `name`. # ServerResult > **ServerResult** = { `found`: `false`; } | { `events`: `object`\[]; `found`: `true`; `missingPermissions`: `string` | `null`; `periodStart`: `string`; `profile`: [`ServerProfile`](/Shardlens/reference/sdk/shardlens/client/interfaces/serverprofile/); `uniqueUsersThisPeriod`: `number` | `null`; } Defined in: [packages/client/src/results.ts:235](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/results.ts#L235) Answer to a `server` query. `found` is `false` for a server the collector has never seen. ## Union Members [Section titled “Union Members”](#union-members) ### Type Literal [Section titled “Type Literal”](#type-literal) { `found`: `false`; } *** ### Type Literal [Section titled “Type Literal”](#type-literal-1) { `events`: `object`\[]; `found`: `true`; `missingPermissions`: `string` | `null`; `periodStart`: `string`; `profile`: [`ServerProfile`](/Shardlens/reference/sdk/shardlens/client/interfaces/serverprofile/); `uniqueUsersThisPeriod`: `number` | `null`; } #### events [Section titled “events”](#events) > **events**: `object`\[] The last 100 times the bot joined or left, or the server went down or came back. Newest first. #### found [Section titled “found”](#found) > **found**: `true` #### missingPermissions [Section titled “missingPermissions”](#missingpermissions) > **missingPermissions**: `string` | `null` The permission bits Settings lists as required that the bot lacks here, as a decimal string (`'0'` for none). `null` when no permissions are required or the bot’s are unknown. #### periodStart [Section titled “periodStart”](#periodstart) > **periodStart**: `string` First day of the current salt period. #### profile [Section titled “profile”](#profile) > **profile**: [`ServerProfile`](/Shardlens/reference/sdk/shardlens/client/interfaces/serverprofile/) #### uniqueUsersThisPeriod [Section titled “uniqueUsersThisPeriod”](#uniqueusersthisperiod) > **uniqueUsersThisPeriod**: `number` | `null` # Stat > **Stat** = `"count"` | `"sum"` | `"avg"` | `"p50"` | `"p95"` | `"p99"` Defined in: [packages/client/src/specs.ts:59](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L59) How a metric’s rows are combined. The percentiles are of response time, in milliseconds. Default `'count'`. # Step > **Step** = { `name`: `string`; `type`: `"event"`; } | { `name`: `string`; `type`: `"command"`; } Defined in: [packages/client/src/specs.ts:62](https://github.com/Kkkermit/Shardlens/blob/main/packages/client/src/specs.ts#L62) One step of a funnel or a cohort: a custom event or a command, by name. # BoundedQueue Defined in: [packages/core/src/queue.ts:20](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L20) A bounded, priority-aware FIFO. It never grows past `capacity`: when full, it evicts the oldest item from the lowest non-empty lane at or below the new item’s priority, or refuses the new item if only higher-priority items remain. Every eviction and refusal is counted in [BoundedQueue.dropped](/Shardlens/reference/sdk/shardlens/core/classes/boundedqueue/#dropped), per lane. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### T [Section titled “T”](#t) `T` ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new BoundedQueue**<`T`>(`capacity`): `BoundedQueue`<`T`> Defined in: [packages/core/src/queue.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L27) #### Parameters [Section titled “Parameters”](#parameters) ##### capacity [Section titled “capacity”](#capacity) `number` #### Returns [Section titled “Returns”](#returns) `BoundedQueue`<`T`> ## Properties [Section titled “Properties”](#properties) ### capacity [Section titled “capacity”](#capacity-1) > `readonly` **capacity**: `number` Defined in: [packages/core/src/queue.ts:25](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L25) *** ### dropped [Section titled “dropped”](#dropped) > `readonly` **dropped**: `number`\[] Defined in: [packages/core/src/queue.ts:24](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L24) Per priority. ## Accessors [Section titled “Accessors”](#accessors) ### size [Section titled “size”](#size) #### Get Signature [Section titled “Get Signature”](#get-signature) > **get** **size**(): `number` Defined in: [packages/core/src/queue.ts:32](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L32) ##### Returns [Section titled “Returns”](#returns-1) `number` ## Methods [Section titled “Methods”](#methods) ### laneSize() [Section titled “laneSize()”](#lanesize) > **laneSize**(`priority`): `number` Defined in: [packages/core/src/queue.ts:36](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L36) #### Parameters [Section titled “Parameters”](#parameters-1) ##### priority [Section titled “priority”](#priority) [`Priority`](/Shardlens/reference/sdk/shardlens/core/type-aliases/priority/) #### Returns [Section titled “Returns”](#returns-2) `number` *** ### push() [Section titled “push()”](#push) > **push**(`item`, `priority`): `void` Defined in: [packages/core/src/queue.ts:46](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L46) #### Parameters [Section titled “Parameters”](#parameters-2) ##### item [Section titled “item”](#item) `T` ##### priority [Section titled “priority”](#priority-1) [`Priority`](/Shardlens/reference/sdk/shardlens/core/type-aliases/priority/) #### Returns [Section titled “Returns”](#returns-3) `void` *** ### removeWhere() [Section titled “removeWhere()”](#removewhere) > **removeWhere**(`match`): `number` Defined in: [packages/core/src/queue.ts:102](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L102) Removes every queued item `match` accepts (a user’s events, when they ask for erasure). Returns how many. #### Parameters [Section titled “Parameters”](#parameters-3) ##### match [Section titled “match”](#match) (`item`) => `boolean` #### Returns [Section titled “Returns”](#returns-4) `number` *** ### requeue() [Section titled “requeue()”](#requeue) > **requeue**(`items`): `void` Defined in: [packages/core/src/queue.ts:78](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L78) Puts a failed batch back at the front of its lanes. If the queue filled up meanwhile, the eviction rule applies: lower lanes give way, and within a lane the batch’s oldest items are dropped first. One splice per lane, so a large queue doesn’t pay for every item on every retry. #### Parameters [Section titled “Parameters”](#parameters-4) ##### items [Section titled “items”](#items) readonly [`QueuedItem`](/Shardlens/reference/sdk/shardlens/core/interfaces/queueditem/)<`T`>\[] #### Returns [Section titled “Returns”](#returns-5) `void` *** ### take() [Section titled “take()”](#take) > **take**(`n`): [`QueuedItem`](/Shardlens/reference/sdk/shardlens/core/interfaces/queueditem/)<`T`>\[] Defined in: [packages/core/src/queue.ts:62](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L62) Highest priority first, oldest first within a lane. #### Parameters [Section titled “Parameters”](#parameters-5) ##### n [Section titled “n”](#n) `number` #### Returns [Section titled “Returns”](#returns-6) [`QueuedItem`](/Shardlens/reference/sdk/shardlens/core/interfaces/queueditem/)<`T`>\[] # ShardlensClient Defined in: [packages/core/src/client.ts:323](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L323) The transport half of the SDK: a bounded priority queue, salt bootstrap, sampling, gzip batching, retries and shutdown. Library adapters (such as `@shardlens/discordjs`) turn library events into wire events and enqueue them. Nothing here throws into the caller: every failure is caught, counted in [ClientStats.internalErrors](/Shardlens/reference/sdk/shardlens/core/interfaces/clientstats/#internalerrors) and reported to `on('error')` listeners. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### E [Section titled “E”](#e) `E` *extends* [`WireEvent`](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/) = [`WireEvent`](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/) ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new ShardlensClient**<`E`>(`options`): `ShardlensClient`<`E`> Defined in: [packages/core/src/client.ts:371](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L371) #### Parameters [Section titled “Parameters”](#parameters) ##### options [Section titled “options”](#options) [`ClientOptions`](/Shardlens/reference/sdk/shardlens/core/interfaces/clientoptions/) #### Returns [Section titled “Returns”](#returns) `ShardlensClient`<`E`> ## Accessors [Section titled “Accessors”](#accessors) ### mode [Section titled “mode”](#mode) #### Get Signature [Section titled “Get Signature”](#get-signature) > **get** **mode**(): [`DataMode`](/Shardlens/reference/sdk/shardlens/core/type-aliases/datamode/) | `undefined` Defined in: [packages/core/src/client.ts:425](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L425) The effective data mode: audit only when both the SDK and the collector are in audit mode. ##### Returns [Section titled “Returns”](#returns-1) [`DataMode`](/Shardlens/reference/sdk/shardlens/core/type-aliases/datamode/) | `undefined` *** ### ready [Section titled “ready”](#ready) #### Get Signature [Section titled “Get Signature”](#get-signature-1) > **get** **ready**(): `boolean` Defined in: [packages/core/src/client.ts:420](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L420) True once salts and settings have arrived from the collector (or the dry-run salt is ready). ##### Returns [Section titled “Returns”](#returns-2) `boolean` ## Methods [Section titled “Methods”](#methods) ### count() [Section titled “count()”](#count) > **count**(`name`, `error?`): `void` Defined in: [packages/core/src/client.ts:550](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L550) Increments an internal error counter and notifies listeners. For adapters; never throws. #### Parameters [Section titled “Parameters”](#parameters-1) ##### name [Section titled “name”](#name) `string` ##### error? [Section titled “error?”](#error) `unknown` #### Returns [Section titled “Returns”](#returns-3) `void` *** ### enqueue() [Section titled “enqueue()”](#enqueue) > **enqueue**(`event`, `priority`): `void` Defined in: [packages/core/src/client.ts:437](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L437) Queues an event. Applies sampling. Never throws. #### Parameters [Section titled “Parameters”](#parameters-2) ##### event [Section titled “event”](#event) `E` ##### priority [Section titled “priority”](#priority) [`Priority`](/Shardlens/reference/sdk/shardlens/core/type-aliases/priority/) #### Returns [Section titled “Returns”](#returns-4) `void` *** ### enqueueWithUser() [Section titled “enqueueWithUser()”](#enqueuewithuser) > **enqueueWithUser**(`userId`, `ts`, `priority`, `build`): `void` Defined in: [packages/core/src/client.ts:459](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L459) Queues an event that carries a user hash. The hash is computed in-process with the period’s salt; if the salt hasn’t arrived yet, the event waits in a small bounded buffer (1,000 events, 60 seconds) and is then dropped. #### Parameters [Section titled “Parameters”](#parameters-3) ##### userId [Section titled “userId”](#userid) `string` ##### ts [Section titled “ts”](#ts) `number` ##### priority [Section titled “priority”](#priority-1) [`Priority`](/Shardlens/reference/sdk/shardlens/core/type-aliases/priority/) ##### build [Section titled “build”](#build) (`userHash`) => `E` #### Returns [Section titled “Returns”](#returns-5) `void` *** ### flush() [Section titled “flush()”](#flush) > **flush**(): `Promise`<`void`> Defined in: [packages/core/src/client.ts:593](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L593) Sends queued events now. Concurrent calls share one flush. Never throws. #### Returns [Section titled “Returns”](#returns-6) `Promise`<`void`> *** ### forgetUser() [Section titled “forgetUser()”](#forgetuser) > **forgetUser**(`userId`): `Promise`<{ `erased`: `number`; } | `undefined`> Defined in: [packages/core/src/client.ts:504](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L504) Asks the collector to delete everything stored for a user (right to erasure). Sends the user’s hashes for every salt period still installed; the raw ID is sent only in audit mode, where the collector already holds it encrypted. Resolves to the number of rows removed, or `undefined` if the request could not be made. Never throws. #### Parameters [Section titled “Parameters”](#parameters-4) ##### userId [Section titled “userId”](#userid-1) `string` #### Returns [Section titled “Returns”](#returns-7) `Promise`<{ `erased`: `number`; } | `undefined`> *** ### hashUser() [Section titled “hashUser()”](#hashuser) > **hashUser**(`userId`, `at?`): `Promise`<`string` | `undefined`> Defined in: [packages/core/src/client.ts:489](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L489) Hashes a user ID for the period containing `at`. Returns `undefined` if that period’s salt isn’t available. Use it for erasure requests; event hashing goes through [ShardlensClient.enqueueWithUser](/Shardlens/reference/sdk/shardlens/core/classes/shardlensclient/#enqueuewithuser). #### Parameters [Section titled “Parameters”](#parameters-5) ##### userId [Section titled “userId”](#userid-2) `string` ##### at? [Section titled “at?”](#at) `Date` = `...` #### Returns [Section titled “Returns”](#returns-8) `Promise`<`string` | `undefined`> *** ### idle() [Section titled “idle()”](#idle) > **idle**(`timeoutMs?`): `Promise`<`void`> Defined in: [packages/core/src/client.ts:584](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L584) Resolves once the first settings load has finished and no user hashing is in progress, or after `timeoutMs`. Serverless runtimes call it before [ShardlensClient.flush](/Shardlens/reference/sdk/shardlens/core/classes/shardlensclient/#flush) inside `waitUntil`, so the events of a short-lived request are hashed and sent before the runtime stops. Never throws. #### Parameters [Section titled “Parameters”](#parameters-6) ##### timeoutMs? [Section titled “timeoutMs?”](#timeoutms) `number` = `2_000` #### Returns [Section titled “Returns”](#returns-9) `Promise`<`void`> *** ### on() [Section titled “on()”](#on) > **on**(`event`, `listener`): () => `void` Defined in: [packages/core/src/client.ts:431](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L431) Listens for internal errors. Listener exceptions are swallowed. #### Parameters [Section titled “Parameters”](#parameters-7) ##### event [Section titled “event”](#event-1) `"error"` ##### listener [Section titled “listener”](#listener) `ErrorListener` #### Returns [Section titled “Returns”](#returns-10) () => `void` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(`options?`): `Promise`<`void`> Defined in: [packages/core/src/client.ts:615](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L615) Stops timers and flushes what is queued, giving up after `timeoutMs`. The SDK never installs signal handlers; call this from your own shutdown code. Every call waits for the same flush. Never throws. #### Parameters [Section titled “Parameters”](#parameters-8) ##### options? [Section titled “options?”](#options-1) [`FlushOptions`](/Shardlens/reference/sdk/shardlens/core/interfaces/flushoptions/) #### Returns [Section titled “Returns”](#returns-11) `Promise`<`void`> *** ### stats() [Section titled “stats()”](#stats) > **stats**(): [`ClientStats`](/Shardlens/reference/sdk/shardlens/core/interfaces/clientstats/) Defined in: [packages/core/src/client.ts:563](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L563) #### Returns [Section titled “Returns”](#returns-12) [`ClientStats`](/Shardlens/reference/sdk/shardlens/core/interfaces/clientstats/) # UserHasher Defined in: [packages/core/src/hash.ts:35](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L35) Pseudonymises Discord user IDs inside the bot process: `HMAC-SHA-256(period salt, userId)`, truncated to 16 bytes and formatted as `h1::<32 hex>`. Keyed, because snowflakes are guessable and a plain hash could be reversed. ## Constructors [Section titled “Constructors”](#constructors) ### Constructor [Section titled “Constructor”](#constructor) > **new UserHasher**(): `UserHasher` #### Returns [Section titled “Returns”](#returns) `UserHasher` ## Methods [Section titled “Methods”](#methods) ### deleteSalt() [Section titled “deleteSalt()”](#deletesalt) > **deleteSalt**(`label`): `void` Defined in: [packages/core/src/hash.ts:56](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L56) Removes a period’s salt, such as one the collector has destroyed, and every hash computed with it. #### Parameters [Section titled “Parameters”](#parameters) ##### label [Section titled “label”](#label) `string` #### Returns [Section titled “Returns”](#returns-1) `void` *** ### hash() [Section titled “hash()”](#hash) > **hash**(`userId`, `label`): `Promise`<`string` | `undefined`> Defined in: [packages/core/src/hash.ts:69](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L69) The user hash, or `undefined` when no salt is installed for the period. #### Parameters [Section titled “Parameters”](#parameters-1) ##### userId [Section titled “userId”](#userid) `string` ##### label [Section titled “label”](#label-1) `string` #### Returns [Section titled “Returns”](#returns-2) `Promise`<`string` | `undefined`> *** ### hasSalt() [Section titled “hasSalt()”](#hassalt) > **hasSalt**(`label`): `boolean` Defined in: [packages/core/src/hash.ts:64](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L64) #### Parameters [Section titled “Parameters”](#parameters-2) ##### label [Section titled “label”](#label-2) `string` #### Returns [Section titled “Returns”](#returns-3) `boolean` *** ### labels() [Section titled “labels()”](#labels) > **labels**(): `string`\[] Defined in: [packages/core/src/hash.ts:60](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L60) #### Returns [Section titled “Returns”](#returns-4) `string`\[] *** ### setSalt() [Section titled “setSalt()”](#setsalt) > **setSalt**(`label`, `salt`): `Promise`<`void`> Defined in: [packages/core/src/hash.ts:41](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L41) Installs a period’s salt (32 bytes). Only the three most recently added periods are kept. #### Parameters [Section titled “Parameters”](#parameters-3) ##### label [Section titled “label”](#label-3) `string` ##### salt [Section titled “salt”](#salt) `Uint8Array` #### Returns [Section titled “Returns”](#returns-5) `Promise`<`void`> # avatarHash > **avatarHash**(`value`): `string` | `undefined` Defined in: [packages/core/src/adapter-helpers.ts:37](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/adapter-helpers.ts#L37) A Discord avatar hash, or `undefined` for anything else (no avatar, or an unexpected shape). ## Parameters [Section titled “Parameters”](#parameters) ### value [Section titled “value”](#value) `unknown` ## Returns [Section titled “Returns”](#returns) `string` | `undefined` # backoffMs > **backoffMs**(`attempt`, `random?`): `number` Defined in: [packages/core/src/transport.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/transport.ts#L15) Exponential backoff with equal jitter (half fixed, half random), capped at 60 seconds. ## Parameters [Section titled “Parameters”](#parameters) ### attempt [Section titled “attempt”](#attempt) `number` ### random? [Section titled “random?”](#random) () => `number` ## Returns [Section titled “Returns”](#returns) `number` # bucketOf > **bucketOf**(`ms`): `number` Defined in: [packages/core/src/histogram.ts:20](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L20) Bucket index for a duration. Anything at or below 1 ms, or not a number, goes to bucket 0. ## Parameters [Section titled “Parameters”](#parameters) ### ms [Section titled “ms”](#ms) `number` ## Returns [Section titled “Returns”](#returns) `number` # bucketUpperMs > **bucketUpperMs**(`i`): `number` Defined in: [packages/core/src/histogram.ts:26](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L26) ## Parameters [Section titled “Parameters”](#parameters) ### i [Section titled “i”](#i) `number` ## Returns [Section titled “Returns”](#returns) `number` # compact > **compact**<`T`>(`value`): `T` Defined in: [packages/core/src/adapter-helpers.ts:26](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/adapter-helpers.ts#L26) Copies an object without its `undefined` values, so events stay small on the wire. ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### T [Section titled “T”](#t) `T` *extends* `Record`<`string`, `unknown`> ## Parameters [Section titled “Parameters”](#parameters) ### value [Section titled “value”](#value) `T` ## Returns [Section titled “Returns”](#returns) `T` # cutText > **cutText**(`text`, `max`): `string` Defined in: [packages/core/src/normalise.ts:12](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/normalise.ts#L12) At most `max` UTF-16 units of `text`, cut so it never ends halfway through a character, with NUL and any lone surrogate replaced by U+FFFD: PostgreSQL can’t store either, so the collector refuses an event holding one. ## Parameters [Section titled “Parameters”](#parameters) ### text [Section titled “text”](#text) `string` ### max [Section titled “max”](#max) `number` ## Returns [Section titled “Returns”](#returns) `string` # errorClass > **errorClass**(`error`): `string` Defined in: [packages/core/src/adapter-helpers.ts:4](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/adapter-helpers.ts#L4) Class name of a thrown value, for the `errorClass` field. Never the message, which can hold user input. ## Parameters [Section titled “Parameters”](#parameters) ### error [Section titled “error”](#error) `unknown` ## Returns [Section titled “Returns”](#returns) `string` # errorCode > **errorCode**(`error`): `number` | `undefined` Defined in: [packages/core/src/adapter-helpers.ts:20](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/adapter-helpers.ts#L20) Discord’s numeric JSON error code (`DiscordAPIError.code`), when the thrown value carries one. ## Parameters [Section titled “Parameters”](#parameters) ### error [Section titled “error”](#error) `unknown` ## Returns [Section titled “Returns”](#returns) `number` | `undefined` # gzipJson > **gzipJson**(`value`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> Defined in: [packages/core/src/transport.ts:2](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/transport.ts#L2) Uses the Web-standard `CompressionStream`, so it works in Node, Bun, Deno and Workers. ## Parameters [Section titled “Parameters”](#parameters) ### value [Section titled “value”](#value) `unknown` ## Returns [Section titled “Returns”](#returns) `Promise`<`Uint8Array`<`ArrayBufferLike`>> # isAllowedEndpoint > **isAllowedEndpoint**(`endpoint`): `boolean` Defined in: [packages/core/src/transport.ts:26](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/transport.ts#L26) Whether the SDK may send to this collector URL: HTTPS only, except plain HTTP to a loopback host for local development. URLs with credentials are refused so keys never travel in the URL. ## Parameters [Section titled “Parameters”](#parameters) ### endpoint [Section titled “endpoint”](#endpoint) `string` ## Returns [Section titled “Returns”](#returns) `boolean` # mergeHistograms > **mergeHistograms**(`a`, `b`): [`Histogram`](/Shardlens/reference/sdk/shardlens/core/type-aliases/histogram/) Defined in: [packages/core/src/histogram.ts:35](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L35) ## Parameters [Section titled “Parameters”](#parameters) ### a [Section titled “a”](#a) readonly `number`\[] ### b [Section titled “b”](#b) readonly `number`\[] ## Returns [Section titled “Returns”](#returns) [`Histogram`](/Shardlens/reference/sdk/shardlens/core/type-aliases/histogram/) # newHistogram > **newHistogram**(): [`Histogram`](/Shardlens/reference/sdk/shardlens/core/type-aliases/histogram/) Defined in: [packages/core/src/histogram.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L15) ## Returns [Section titled “Returns”](#returns) [`Histogram`](/Shardlens/reference/sdk/shardlens/core/type-aliases/histogram/) # nextPeriodStart > **nextPeriodStart**(`period`, `at`): `number` Defined in: [packages/core/src/client.ts:266](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L266) Start of the next salt period after `at`, in epoch ms (UTC). ## Parameters [Section titled “Parameters”](#parameters) ### period [Section titled “period”](#period) [`SaltPeriod`](/Shardlens/reference/sdk/shardlens/core/type-aliases/saltperiod/) ### at [Section titled “at”](#at) `Date` ## Returns [Section titled “Returns”](#returns) `number` # normaliseCustomId > **normaliseCustomId**(`customId`): `string` Defined in: [packages/core/src/normalise.ts:23](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/normalise.ts#L23) Turns a custom ID into a pattern without IDs or numbers: `ticket:close:112233445566778899` → `ticket:close:*`. UUIDs go first, as a whole: their digits alone would leave the letters behind. ## Parameters [Section titled “Parameters”](#parameters) ### customId [Section titled “customId”](#customid) `string` ## Returns [Section titled “Returns”](#returns) `string` # observe > **observe**(`hist`, `ms`, `weight?`): `void` Defined in: [packages/core/src/histogram.ts:30](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L30) ## Parameters [Section titled “Parameters”](#parameters) ### hist [Section titled “hist”](#hist) [`Histogram`](/Shardlens/reference/sdk/shardlens/core/type-aliases/histogram/) ### ms [Section titled “ms”](#ms) `number` ### weight? [Section titled “weight?”](#weight) `number` = `1` ## Returns [Section titled “Returns”](#returns) `void` # periodLabel > **periodLabel**(`period`, `at?`): `string` Defined in: [packages/core/src/hash.ts:7](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L7) Period label, always in UTC: `2026-11` (month), `2026-W46` (ISO week) or `2026-11-13` (day). ## Parameters [Section titled “Parameters”](#parameters) ### period [Section titled “period”](#period) [`SaltPeriod`](/Shardlens/reference/sdk/shardlens/core/type-aliases/saltperiod/) ### at? [Section titled “at?”](#at) `Date` = `...` ## Returns [Section titled “Returns”](#returns) `string` # quantile > **quantile**(`hist`, `q`): `number` | `undefined` Defined in: [packages/core/src/histogram.ts:42](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L42) Estimated quantile (`q` in 0–1): the upper bound of the bucket where the cumulative share first reaches `q`. ## Parameters [Section titled “Parameters”](#parameters) ### hist [Section titled “hist”](#hist) readonly `number`\[] ### q [Section titled “q”](#q) `number` ## Returns [Section titled “Returns”](#returns) `number` | `undefined` # recordedOptionValue > **recordedOptionValue**(`value`, `type?`): `string` | `number` | `boolean` | `undefined` Defined in: [packages/core/src/adapter-helpers.ts:50](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/adapter-helpers.ts#L50) How an allow-listed option’s value is recorded (`captureOptionValues`), or `undefined` when it must not be: never a user, channel, role, mentionable or attachment option, nor a value holding a Discord ID, which a user can type. Strings have secrets redacted and are cut to 100 characters. ## Parameters [Section titled “Parameters”](#parameters) ### value [Section titled “value”](#value) `unknown` ### type? [Section titled “type?”](#type) `number` ## Returns [Section titled “Returns”](#returns) `string` | `number` | `boolean` | `undefined` # redactSecrets > **redactSecrets**(`text`): `string` Defined in: [packages/core/src/normalise.ts:41](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/normalise.ts#L41) Removes anything that looks like a Discord bot token, an interaction or webhook token, an `Authorization` value or a Shardlens API key. Every piece of error text passes through this before it is sent or logged. ## Parameters [Section titled “Parameters”](#parameters) ### text [Section titled “text”](#text) `string` ## Returns [Section titled “Returns”](#returns) `string` # sanitiseCustomProps > **sanitiseCustomProps**(`props`): [`CustomProps`](/Shardlens/reference/sdk/shardlens/core/type-aliases/customprops/) | `undefined` Defined in: [packages/core/src/custom-events.ts:38](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L38) Copies custom event properties if they fit the limits (2 KB, 64-character keys, 256-character strings), with secrets redacted and NUL or broken characters in keys and strings replaced. ## Parameters [Section titled “Parameters”](#parameters) ### props [Section titled “props”](#props) `unknown` ## Returns [Section titled “Returns”](#returns) [`CustomProps`](/Shardlens/reference/sdk/shardlens/core/type-aliases/customprops/) | `undefined` # translateEvent > **translateEvent**(`event`, `sink`): `void` Defined in: [packages/core/src/exporter.ts:148](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L148) Turns one wire event into measurements, so every exporter reports the same thing. ## Parameters [Section titled “Parameters”](#parameters) ### event [Section titled “event”](#event) [`WireEvent`](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/) ### sink [Section titled “sink”](#sink) [`MetricSink`](/Shardlens/reference/sdk/shardlens/core/interfaces/metricsink/) ## Returns [Section titled “Returns”](#returns) `void` # uuidv7 > **uuidv7**(`now?`): `string` Defined in: [packages/core/src/uuidv7.ts:12](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/uuidv7.ts#L12) RFC 9562 UUIDv7. Event IDs sort by time, so the collector can drop retried duplicates with a primary-key conflict that stays inside one time partition. ## Parameters [Section titled “Parameters”](#parameters) ### now? [Section titled “now?”](#now) `number` = `...` ## Returns [Section titled “Returns”](#returns) `string` # uuidv7Timestamp > **uuidv7Timestamp**(`id`): `number` Defined in: [packages/core/src/uuidv7.ts:32](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/uuidv7.ts#L32) ## Parameters [Section titled “Parameters”](#parameters) ### id [Section titled “id”](#id) `string` ## Returns [Section titled “Returns”](#returns) `number` # ClientOptions Defined in: [packages/core/src/client.ts:33](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L33) ## Properties [Section titled “Properties”](#properties) ### apiKey? [Section titled “apiKey?”](#apikey) > `optional` **apiKey?**: `string` Defined in: [packages/core/src/client.ts:40](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L40) Ingest-only key (`slk_ingest_…`). *** ### dryRun? [Section titled “dryRun?”](#dryrun) > `optional` **dryRun?**: `boolean` Defined in: [packages/core/src/client.ts:61](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L61) Print events instead of sending them. Hashes use a throwaway local salt. *** ### endpoint? [Section titled “endpoint?”](#endpoint) > `optional` **endpoint?**: `string` Defined in: [packages/core/src/client.ts:38](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L38) Collector base URL. HTTPS, or HTTP to localhost only. Leave out together with `apiKey` to run without a collector (exporters only). *** ### environment? [Section titled “environment?”](#environment) > `optional` **environment?**: `string` Defined in: [packages/core/src/client.ts:49](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L49) Separates staging from live. Default `'production'`. *** ### exporters? [Section titled “exporters?”](#exporters) > `optional` **exporters?**: readonly [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/core/interfaces/shardlensexporter/)\[] Defined in: [packages/core/src/client.ts:42](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L42) In-process metrics exporters (Prometheus, OpenTelemetry). They receive every event, without users. *** ### fetch? [Section titled “fetch?”](#fetch) > `optional` **fetch?**: {(`input`, `init?`): `Promise`<`Response`>; (`input`, `init?`): `Promise`<`Response`>; } Defined in: [packages/core/src/client.ts:66](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L66) Override for tests and unusual runtimes. #### Call Signature [Section titled “Call Signature”](#call-signature) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters) ###### input [Section titled “input”](#input) `URL` | `RequestInfo` ###### init? [Section titled “init?”](#init) `RequestInit` ##### Returns [Section titled “Returns”](#returns) `Promise`<`Response`> #### Call Signature [Section titled “Call Signature”](#call-signature-1) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters-1) ###### input [Section titled “input”](#input-1) `string` | `URL` | `Request` ###### init? [Section titled “init?”](#init-1) `RequestInit` ##### Returns [Section titled “Returns”](#returns-1) `Promise`<`Response`> *** ### flushIntervalMs? [Section titled “flushIntervalMs?”](#flushintervalms) > `optional` **flushIntervalMs?**: `number` Defined in: [packages/core/src/client.ts:53](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L53) Flush interval. Default 5,000 ms. *** ### logger? [Section titled “logger?”](#logger) > `optional` **logger?**: [`Logger`](/Shardlens/reference/sdk/shardlens/core/interfaces/logger/) Defined in: [packages/core/src/client.ts:64](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L64) *** ### maxBatchSize? [Section titled “maxBatchSize?”](#maxbatchsize) > `optional` **maxBatchSize?**: `number` Defined in: [packages/core/src/client.ts:55](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L55) Events per batch (max 500). Default 500. *** ### maxQueueSize? [Section titled “maxQueueSize?”](#maxqueuesize) > `optional` **maxQueueSize?**: `number` Defined in: [packages/core/src/client.ts:57](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L57) Memory ceiling, in events. Default 10,000. *** ### mode? [Section titled “mode?”](#mode) > `optional` **mode?**: [`DataMode`](/Shardlens/reference/sdk/shardlens/core/type-aliases/datamode/) Defined in: [packages/core/src/client.ts:47](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L47) `'audit'` only takes effect when the collector is also in audit mode. Default `'privacy'`. *** ### random? [Section titled “random?”](#random) > `optional` **random?**: () => `number` Defined in: [packages/core/src/client.ts:68](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L68) Randomness in \[0, 1), for jitter and sampling. Injectable for tests. #### Returns [Section titled “Returns”](#returns-2) `number` *** ### release? [Section titled “release?”](#release) > `optional` **release?**: `string` Defined in: [packages/core/src/client.ts:51](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L51) Your bot’s version, to compare releases. *** ### sampleRate? [Section titled “sampleRate?”](#samplerate) > `optional` **sampleRate?**: `Readonly`<`Record`<`string`, `number`>> Defined in: [packages/core/src/client.ts:59](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L59) Sample rate per event type, in (0, 1]. Kept events carry `weight = 1 / rate`. The collector’s settings win. *** ### sdk [Section titled “sdk”](#sdk) > **sdk**: `object` Defined in: [packages/core/src/client.ts:45](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L45) #### name [Section titled “name”](#name) > **name**: `string` #### version [Section titled “version”](#version) > **version**: `string` *** ### source? [Section titled “source?”](#source) > `optional` **source?**: () => [`SourceInfo`](/Shardlens/reference/sdk/shardlens/core/interfaces/sourceinfo/) Defined in: [packages/core/src/client.ts:63](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L63) Called for the current shard/cluster information each time a batch is built. #### Returns [Section titled “Returns”](#returns-3) [`SourceInfo`](/Shardlens/reference/sdk/shardlens/core/interfaces/sourceinfo/) *** ### spool? [Section titled “spool?”](#spool) > `optional` **spool?**: [`EventSpool`](/Shardlens/reference/sdk/shardlens/core/interfaces/eventspool/) Defined in: [packages/core/src/client.ts:44](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L44) Durable overflow for long collector outages (for example a disk spool). See [EventSpool](/Shardlens/reference/sdk/shardlens/core/interfaces/eventspool/). # ClientStats Defined in: [packages/core/src/client.ts:77](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L77) A snapshot of the SDK’s own health, also sent as the `sdk_health` event. ## Properties [Section titled “Properties”](#properties) ### dropped [Section titled “dropped”](#dropped) > **dropped**: `Record`<`string`, `number`> Defined in: [packages/core/src/client.ts:80](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L80) *** ### failedFlushes [Section titled “failedFlushes”](#failedflushes) > **failedFlushes**: `number` Defined in: [packages/core/src/client.ts:81](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L81) *** ### internalErrors [Section titled “internalErrors”](#internalerrors) > **internalErrors**: `Record`<`string`, `number`> Defined in: [packages/core/src/client.ts:82](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L82) *** ### mode [Section titled “mode”](#mode) > **mode**: [`DataMode`](/Shardlens/reference/sdk/shardlens/core/type-aliases/datamode/) | `undefined` Defined in: [packages/core/src/client.ts:84](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L84) *** ### pendingSalt [Section titled “pendingSalt”](#pendingsalt) > **pendingSalt**: `number` Defined in: [packages/core/src/client.ts:79](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L79) *** ### queueDepth [Section titled “queueDepth”](#queuedepth) > **queueDepth**: `number` Defined in: [packages/core/src/client.ts:78](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L78) *** ### ready [Section titled “ready”](#ready) > **ready**: `boolean` Defined in: [packages/core/src/client.ts:83](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L83) *** ### replayed [Section titled “replayed”](#replayed) > **replayed**: `number` Defined in: [packages/core/src/client.ts:88](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L88) Spooled events the collector has since accepted. *** ### spooled [Section titled “spooled”](#spooled) > **spooled**: `number` Defined in: [packages/core/src/client.ts:86](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L86) Events written to the spool during this process’s lifetime (0 without a spool). # CustomEvents Defined in: [packages/core/src/custom-events.ts:22](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L22) Register your custom events here for typed `track()` calls. Name the Shardlens package your bot installs (`@shardlens/discordjs` or `@shardlens/http`): with pnpm, a bot can’t see `@shardlens/core` itself. ## Example [Section titled “Example”](#example) ```ts declare module '@shardlens/discordjs' { interface CustomEvents { ticket_opened: { category: 'billing' | 'support' }; } } lens.track('ticket_opened', { category: 'billing' }); ``` # EventSpool Defined in: [packages/core/src/spool.ts:8](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/spool.ts#L8) Durable overflow storage for long collector outages. The client writes batches when memory fills up and on `shutdown()`, replays the oldest first, and acknowledges a batch only once the collector accepted it. Batches never contain raw user IDs. Implementations may throw; the client catches and counts every failure. ## Methods [Section titled “Methods”](#methods) ### ack() [Section titled “ack()”](#ack) > **ack**(`id`): `Promise`<`void`> Defined in: [packages/core/src/spool.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/spool.ts#L13) #### Parameters [Section titled “Parameters”](#parameters) ##### id [Section titled “id”](#id) `string` #### Returns [Section titled “Returns”](#returns) `Promise`<`void`> *** ### drop()? [Section titled “drop()?”](#drop) > `optional` **drop**(`match`): `Promise`<`number`> Defined in: [packages/core/src/spool.ts:18](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/spool.ts#L18) Removes the stored events `match` accepts, such as those of a user who asked for erasure, and resolves to how many. Optional: without it, an erasure doesn’t reach events already on disk. #### Parameters [Section titled “Parameters”](#parameters-1) ##### match [Section titled “match”](#match) (`event`) => `boolean` #### Returns [Section titled “Returns”](#returns-1) `Promise`<`number`> *** ### next() [Section titled “next()”](#next) > **next**(): `Promise`<{ `events`: [`WireEvent`](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/)\[]; `id`: `string`; } | `undefined`> Defined in: [packages/core/src/spool.ts:12](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/spool.ts#L12) The oldest stored batch, or `undefined` when the spool is empty. #### Returns [Section titled “Returns”](#returns-2) `Promise`<{ `events`: [`WireEvent`](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/)\[]; `id`: `string`; } | `undefined`> *** ### write() [Section titled “write()”](#write) > **write**(`events`): `Promise`<`boolean`> Defined in: [packages/core/src/spool.ts:10](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/spool.ts#L10) Persists a batch. Resolves `false` when it can’t be stored (for example the size cap is reached). #### Parameters [Section titled “Parameters”](#parameters-2) ##### events [Section titled “events”](#events) readonly [`WireEvent`](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/)\[] #### Returns [Section titled “Returns”](#returns-3) `Promise`<`boolean`> # ExporterMetric Defined in: [packages/core/src/exporter.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L15) One exported instrument. Names are neutral; each exporter applies its own naming convention. ## Properties [Section titled “Properties”](#properties) ### description [Section titled “description”](#description) > `readonly` **description**: `string` Defined in: [packages/core/src/exporter.ts:17](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L17) *** ### kind [Section titled “kind”](#kind) > `readonly` **kind**: `"gauge"` | `"counter"` | `"histogram"` Defined in: [packages/core/src/exporter.ts:16](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L16) *** ### labels [Section titled “labels”](#labels) > `readonly` **labels**: readonly `string`\[] Defined in: [packages/core/src/exporter.ts:20](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L20) Label names. Never a user or server ID. *** ### unit [Section titled “unit”](#unit) > `readonly` **unit**: `"1"` | `"seconds"` | `"bytes"` Defined in: [packages/core/src/exporter.ts:18](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L18) # FlushOptions Defined in: [packages/core/src/client.ts:71](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L71) ## Properties [Section titled “Properties”](#properties) ### timeoutMs? [Section titled “timeoutMs?”](#timeoutms) > `optional` **timeoutMs?**: `number` Defined in: [packages/core/src/client.ts:73](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L73) Give up after this long. Default 2,000 ms. # Logger Defined in: [packages/core/src/client.ts:20](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L20) Where log lines go. Every message is passed through `redactSecrets` first. ## Methods [Section titled “Methods”](#methods) ### debug()? [Section titled “debug()?”](#debug) > `optional` **debug**(`message`): `void` Defined in: [packages/core/src/client.ts:21](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L21) #### Parameters [Section titled “Parameters”](#parameters) ##### message [Section titled “message”](#message) `string` #### Returns [Section titled “Returns”](#returns) `void` *** ### info()? [Section titled “info()?”](#info) > `optional` **info**(`message`): `void` Defined in: [packages/core/src/client.ts:22](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L22) #### Parameters [Section titled “Parameters”](#parameters-1) ##### message [Section titled “message”](#message-1) `string` #### Returns [Section titled “Returns”](#returns-1) `void` *** ### warn() [Section titled “warn()”](#warn) > **warn**(`message`): `void` Defined in: [packages/core/src/client.ts:23](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L23) #### Parameters [Section titled “Parameters”](#parameters-2) ##### message [Section titled “message”](#message-2) `string` #### Returns [Section titled “Returns”](#returns-2) `void` # MetricSink Defined in: [packages/core/src/exporter.ts:125](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L125) What an exporter implements to receive translated measurements. ## Methods [Section titled “Methods”](#methods) ### add() [Section titled “add()”](#add) > **add**(`metric`, `labels`, `value`): `void` Defined in: [packages/core/src/exporter.ts:126](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L126) #### Parameters [Section titled “Parameters”](#parameters) ##### metric [Section titled “metric”](#metric) `"interactions"` | `"guilds"` | `"interaction_response"` | `"interaction_handler"` | `"interaction_errors"` | `"rest_requests"` | `"rest_invalid_requests"` | `"ratelimits"` | `"shard_events"` | `"guild_events"` | `"custom_events"` | `"entitlements"` | `"shard_ping"` | `"eventloop_delay_p99"` | `"memory"` | `"cache_size"` | `"identify_remaining"` ##### labels [Section titled “labels”](#labels) [`MetricLabels`](/Shardlens/reference/sdk/shardlens/core/type-aliases/metriclabels/) ##### value [Section titled “value”](#value) `number` #### Returns [Section titled “Returns”](#returns) `void` *** ### record() [Section titled “record()”](#record) > **record**(`metric`, `labels`, `value`): `void` Defined in: [packages/core/src/exporter.ts:127](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L127) #### Parameters [Section titled “Parameters”](#parameters-1) ##### metric [Section titled “metric”](#metric-1) `"interactions"` | `"guilds"` | `"interaction_response"` | `"interaction_handler"` | `"interaction_errors"` | `"rest_requests"` | `"rest_invalid_requests"` | `"ratelimits"` | `"shard_events"` | `"guild_events"` | `"custom_events"` | `"entitlements"` | `"shard_ping"` | `"eventloop_delay_p99"` | `"memory"` | `"cache_size"` | `"identify_remaining"` ##### labels [Section titled “labels”](#labels-1) [`MetricLabels`](/Shardlens/reference/sdk/shardlens/core/type-aliases/metriclabels/) ##### value [Section titled “value”](#value-1) `number` #### Returns [Section titled “Returns”](#returns-1) `void` *** ### set() [Section titled “set()”](#set) > **set**(`metric`, `labels`, `value`): `void` Defined in: [packages/core/src/exporter.ts:128](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L128) #### Parameters [Section titled “Parameters”](#parameters-2) ##### metric [Section titled “metric”](#metric-2) `"interactions"` | `"guilds"` | `"interaction_response"` | `"interaction_handler"` | `"interaction_errors"` | `"rest_requests"` | `"rest_invalid_requests"` | `"ratelimits"` | `"shard_events"` | `"guild_events"` | `"custom_events"` | `"entitlements"` | `"shard_ping"` | `"eventloop_delay_p99"` | `"memory"` | `"cache_size"` | `"identify_remaining"` ##### labels [Section titled “labels”](#labels-2) [`MetricLabels`](/Shardlens/reference/sdk/shardlens/core/type-aliases/metriclabels/) ##### value [Section titled “value”](#value-2) `number` #### Returns [Section titled “Returns”](#returns-2) `void` # QueuedItem Defined in: [packages/core/src/queue.ts:10](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L10) ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### T [Section titled “T”](#t) `T` ## Properties [Section titled “Properties”](#properties) ### item [Section titled “item”](#item) > **item**: `T` Defined in: [packages/core/src/queue.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L11) *** ### priority [Section titled “priority”](#priority) > **priority**: [`Priority`](/Shardlens/reference/sdk/shardlens/core/type-aliases/priority/) Defined in: [packages/core/src/queue.ts:12](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L12) # ShardlensExporter Defined in: [packages/core/src/exporter.ts:7](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L7) Receives every event the SDK records, in-process and before sampling. Events never carry a user. Implementations must not label metrics by user or server ID, do I/O in `observe`, or throw. ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > `readonly` **name**: `string` Defined in: [packages/core/src/exporter.ts:9](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L9) Short name, used when counting errors (`exporter:`). ## Methods [Section titled “Methods”](#methods) ### observe() [Section titled “observe()”](#observe) > **observe**(`event`): `void` Defined in: [packages/core/src/exporter.ts:10](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L10) #### Parameters [Section titled “Parameters”](#parameters) ##### event [Section titled “event”](#event) [`WireEvent`](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/) #### Returns [Section titled “Returns”](#returns) `void` *** ### shutdown()? [Section titled “shutdown()?”](#shutdown) > `optional` **shutdown**(): `void` | `Promise`<`void`> Defined in: [packages/core/src/exporter.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L11) #### Returns [Section titled “Returns”](#returns-1) `void` | `Promise`<`void`> # SourceInfo Defined in: [packages/core/src/client.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L27) Identifies the sending process: shards it owns, cluster (hybrid sharding) and a host label. ## Properties [Section titled “Properties”](#properties) ### cluster? [Section titled “cluster?”](#cluster) > `optional` **cluster?**: `number` Defined in: [packages/core/src/client.ts:29](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L29) *** ### instance [Section titled “instance”](#instance) > **instance**: `string` Defined in: [packages/core/src/client.ts:30](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L30) *** ### shards [Section titled “shards”](#shards) > **shards**: `number`\[] Defined in: [packages/core/src/client.ts:28](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L28) # WireEvent Defined in: [packages/core/src/client.ts:10](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L10) The fields every wire event has. Adapters pass full event objects from `@shardlens/schema`. ## Properties [Section titled “Properties”](#properties) ### id [Section titled “id”](#id) > **id**: `string` Defined in: [packages/core/src/client.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L11) *** ### ts [Section titled “ts”](#ts) > **ts**: `number` Defined in: [packages/core/src/client.ts:12](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L12) *** ### type [Section titled “type”](#type) > **type**: `string` Defined in: [packages/core/src/client.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L13) *** ### weight? [Section titled “weight?”](#weight) > `optional` **weight?**: `number` Defined in: [packages/core/src/client.ts:14](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L14) # @shardlens/core `@shardlens/core`: the library-agnostic heart of the Shardlens SDK. Zero runtime dependencies and Web-standard APIs only (`fetch`, Web Crypto, `CompressionStream`), so it runs on Node 22.12+, Bun, Deno and Cloudflare Workers. ## Classes [Section titled “Classes”](#classes) * [BoundedQueue](/Shardlens/reference/sdk/shardlens/core/classes/boundedqueue/) * [ShardlensClient](/Shardlens/reference/sdk/shardlens/core/classes/shardlensclient/) * [UserHasher](/Shardlens/reference/sdk/shardlens/core/classes/userhasher/) ## Interfaces [Section titled “Interfaces”](#interfaces) * [ClientOptions](/Shardlens/reference/sdk/shardlens/core/interfaces/clientoptions/) * [ClientStats](/Shardlens/reference/sdk/shardlens/core/interfaces/clientstats/) * [CustomEvents](/Shardlens/reference/sdk/shardlens/core/interfaces/customevents/) * [EventSpool](/Shardlens/reference/sdk/shardlens/core/interfaces/eventspool/) * [ExporterMetric](/Shardlens/reference/sdk/shardlens/core/interfaces/exportermetric/) * [FlushOptions](/Shardlens/reference/sdk/shardlens/core/interfaces/flushoptions/) * [Logger](/Shardlens/reference/sdk/shardlens/core/interfaces/logger/) * [MetricSink](/Shardlens/reference/sdk/shardlens/core/interfaces/metricsink/) * [QueuedItem](/Shardlens/reference/sdk/shardlens/core/interfaces/queueditem/) * [ShardlensExporter](/Shardlens/reference/sdk/shardlens/core/interfaces/shardlensexporter/) * [SourceInfo](/Shardlens/reference/sdk/shardlens/core/interfaces/sourceinfo/) * [WireEvent](/Shardlens/reference/sdk/shardlens/core/interfaces/wireevent/) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [CustomEventName](/Shardlens/reference/sdk/shardlens/core/type-aliases/customeventname/) * [CustomEventProps](/Shardlens/reference/sdk/shardlens/core/type-aliases/customeventprops/) * [CustomProps](/Shardlens/reference/sdk/shardlens/core/type-aliases/customprops/) * [CustomPropValue](/Shardlens/reference/sdk/shardlens/core/type-aliases/custompropvalue/) * [DataMode](/Shardlens/reference/sdk/shardlens/core/type-aliases/datamode/) * [ExporterMetricName](/Shardlens/reference/sdk/shardlens/core/type-aliases/exportermetricname/) * [Histogram](/Shardlens/reference/sdk/shardlens/core/type-aliases/histogram/) * [MetricLabels](/Shardlens/reference/sdk/shardlens/core/type-aliases/metriclabels/) * [Priority](/Shardlens/reference/sdk/shardlens/core/type-aliases/priority/) * [SaltPeriod](/Shardlens/reference/sdk/shardlens/core/type-aliases/saltperiod/) ## Variables [Section titled “Variables”](#variables) * [BACKOFF_MAX_MS](/Shardlens/reference/sdk/shardlens/core/variables/backoff_max_ms/) * [BACKOFF_MIN_MS](/Shardlens/reference/sdk/shardlens/core/variables/backoff_min_ms/) * [BUCKETS](/Shardlens/reference/sdk/shardlens/core/variables/buckets/) * [CUSTOM_EVENT_NAME](/Shardlens/reference/sdk/shardlens/core/variables/custom_event_name/) * [DEFAULT_DURATION_BUCKETS](/Shardlens/reference/sdk/shardlens/core/variables/default_duration_buckets/) * [EXPORTER_METRICS](/Shardlens/reference/sdk/shardlens/core/variables/exporter_metrics/) * [HASH_BYTES](/Shardlens/reference/sdk/shardlens/core/variables/hash_bytes/) * [HASH_VERSION](/Shardlens/reference/sdk/shardlens/core/variables/hash_version/) * [MAX_CUSTOM_ID_LENGTH](/Shardlens/reference/sdk/shardlens/core/variables/max_custom_id_length/) * [MAX_CUSTOM_PROPS_BYTES](/Shardlens/reference/sdk/shardlens/core/variables/max_custom_props_bytes/) * [MAX_MS](/Shardlens/reference/sdk/shardlens/core/variables/max_ms/) * [PRIORITIES](/Shardlens/reference/sdk/shardlens/core/variables/priorities/) ## Functions [Section titled “Functions”](#functions) * [avatarHash](/Shardlens/reference/sdk/shardlens/core/functions/avatarhash/) * [backoffMs](/Shardlens/reference/sdk/shardlens/core/functions/backoffms/) * [bucketOf](/Shardlens/reference/sdk/shardlens/core/functions/bucketof/) * [bucketUpperMs](/Shardlens/reference/sdk/shardlens/core/functions/bucketupperms/) * [compact](/Shardlens/reference/sdk/shardlens/core/functions/compact/) * [cutText](/Shardlens/reference/sdk/shardlens/core/functions/cuttext/) * [errorClass](/Shardlens/reference/sdk/shardlens/core/functions/errorclass/) * [errorCode](/Shardlens/reference/sdk/shardlens/core/functions/errorcode/) * [gzipJson](/Shardlens/reference/sdk/shardlens/core/functions/gzipjson/) * [isAllowedEndpoint](/Shardlens/reference/sdk/shardlens/core/functions/isallowedendpoint/) * [mergeHistograms](/Shardlens/reference/sdk/shardlens/core/functions/mergehistograms/) * [newHistogram](/Shardlens/reference/sdk/shardlens/core/functions/newhistogram/) * [nextPeriodStart](/Shardlens/reference/sdk/shardlens/core/functions/nextperiodstart/) * [normaliseCustomId](/Shardlens/reference/sdk/shardlens/core/functions/normalisecustomid/) * [observe](/Shardlens/reference/sdk/shardlens/core/functions/observe/) * [periodLabel](/Shardlens/reference/sdk/shardlens/core/functions/periodlabel/) * [quantile](/Shardlens/reference/sdk/shardlens/core/functions/quantile/) * [recordedOptionValue](/Shardlens/reference/sdk/shardlens/core/functions/recordedoptionvalue/) * [redactSecrets](/Shardlens/reference/sdk/shardlens/core/functions/redactsecrets/) * [sanitiseCustomProps](/Shardlens/reference/sdk/shardlens/core/functions/sanitisecustomprops/) * [translateEvent](/Shardlens/reference/sdk/shardlens/core/functions/translateevent/) * [uuidv7](/Shardlens/reference/sdk/shardlens/core/functions/uuidv7/) * [uuidv7Timestamp](/Shardlens/reference/sdk/shardlens/core/functions/uuidv7timestamp/) # CustomEventName > **CustomEventName** = \[keyof [`CustomEvents`](/Shardlens/reference/sdk/shardlens/core/interfaces/customevents/)] *extends* \[`never`] ? `string` : keyof [`CustomEvents`](/Shardlens/reference/sdk/shardlens/core/interfaces/customevents/) & `string` Defined in: [packages/core/src/custom-events.ts:25](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L25) Event names accepted by `track()`: your registered names, or any string if you registered none. # CustomEventProps > **CustomEventProps**<`N`> = `N` *extends* keyof [`CustomEvents`](/Shardlens/reference/sdk/shardlens/core/interfaces/customevents/) ? [`CustomEvents`](/Shardlens/reference/sdk/shardlens/core/interfaces/customevents/)\[`N`] : [`CustomProps`](/Shardlens/reference/sdk/shardlens/core/type-aliases/customprops/) Defined in: [packages/core/src/custom-events.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L27) ## Type Parameters [Section titled “Type Parameters”](#type-parameters) ### N [Section titled “N”](#n) `N` *extends* `string` # CustomProps > **CustomProps** = `Record`<`string`, [`CustomPropValue`](/Shardlens/reference/sdk/shardlens/core/type-aliases/custompropvalue/)> Defined in: [packages/core/src/custom-events.ts:5](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L5) # CustomPropValue > **CustomPropValue** = `string` | `number` | `boolean` | `null` Defined in: [packages/core/src/custom-events.ts:3](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L3) # DataMode > **DataMode** = `"privacy"` | `"audit"` Defined in: [packages/core/src/client.ts:17](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/client.ts#L17) # ExporterMetricName > **ExporterMetricName** = keyof *typeof* [`EXPORTER_METRICS`](/Shardlens/reference/sdk/shardlens/core/variables/exporter_metrics/) Defined in: [packages/core/src/exporter.ts:121](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L121) # Histogram > **Histogram** = `number`\[] Defined in: [packages/core/src/histogram.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L13) # MetricLabels > **MetricLabels** = `Readonly`<`Record`<`string`, `string`>> Defined in: [packages/core/src/exporter.ts:122](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L122) # Priority > **Priority** = `0` | `1` | `2` | `3` Defined in: [packages/core/src/queue.ts:6](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L6) Drop priority for queued events. When the queue is full, lower lanes are evicted first: `0` gauges, `1` REST windows and guild updates, `2` custom events, rate limits and app info, `3` interactions and server lifecycle (dropped last). # SaltPeriod > **SaltPeriod** = `"day"` | `"week"` | `"month"` Defined in: [packages/core/src/hash.ts:4](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L4) How long one salt lives. Shorter periods are stricter but cannot produce weekly or monthly unique users. # BACKOFF_MAX_MS > `const` **BACKOFF_MAX_MS**: `60000` = `60_000` Defined in: [packages/core/src/transport.ts:12](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/transport.ts#L12) # BACKOFF_MIN_MS > `const` **BACKOFF_MIN_MS**: `1000` = `1_000` Defined in: [packages/core/src/transport.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/transport.ts#L11) # BUCKETS > `const` **BUCKETS**: `40` = `40` Defined in: [packages/core/src/histogram.ts:6](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L6) Latency histograms: 40 log-scale buckets covering 1 ms to 60 s. They merge by element-wise addition, so percentiles survive rollups. `HISTOGRAM_BUCKETS` in `@shardlens/schema` and the collector’s SQL `shardlens_bucket()` must match. # CUSTOM_EVENT_NAME > `const` **CUSTOM_EVENT_NAME**: `RegExp` Defined in: [packages/core/src/custom-events.ts:30](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L30) Custom event names: lower snake case, starting with a letter, up to 64 characters. # DEFAULT_DURATION_BUCKETS > `const` **DEFAULT_DURATION_BUCKETS**: readonly `number`\[] Defined in: [packages/core/src/exporter.ts:24](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L24) Histogram bucket boundaries, in seconds, placed around Discord’s 3-second response deadline. # EXPORTER_METRICS > `const` **EXPORTER_METRICS**: `object` Defined in: [packages/core/src/exporter.ts:30](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/exporter.ts#L30) The instruments every Shardlens exporter registers. Labels are bounded: command names, bucketed REST routes, statuses, shard numbers and custom event names you chose. There is no user or server label anywhere. ## Type Declaration [Section titled “Type Declaration”](#type-declaration) ### cache_size [Section titled “cache_size”](#cache_size) > `readonly` **cache_size**: `object` #### cache_size.description [Section titled “cache_size.description”](#cache_sizedescription) > `readonly` **description**: `"discord.js cache sizes (users, channels)."` = `'discord.js cache sizes (users, channels).'` #### cache_size.kind [Section titled “cache_size.kind”](#cache_sizekind) > `readonly` **kind**: `"gauge"` = `'gauge'` #### cache_size.labels [Section titled “cache_size.labels”](#cache_sizelabels) > `readonly` **labels**: readonly \[`"cache"`] #### cache_size.unit [Section titled “cache_size.unit”](#cache_sizeunit) > `readonly` **unit**: `"1"` = `'1'` ### custom_events [Section titled “custom_events”](#custom_events) > `readonly` **custom_events**: `object` #### custom_events.description [Section titled “custom_events.description”](#custom_eventsdescription) > `readonly` **description**: `"Custom events recorded with track(), by name."` = `'Custom events recorded with track(), by name.'` #### custom_events.kind [Section titled “custom_events.kind”](#custom_eventskind) > `readonly` **kind**: `"counter"` = `'counter'` #### custom_events.labels [Section titled “custom_events.labels”](#custom_eventslabels) > `readonly` **labels**: readonly \[`"name"`] #### custom_events.unit [Section titled “custom_events.unit”](#custom_eventsunit) > `readonly` **unit**: `"1"` = `'1'` ### entitlements [Section titled “entitlements”](#entitlements) > `readonly` **entitlements**: `object` #### entitlements.description [Section titled “entitlements.description”](#entitlementsdescription) > `readonly` **description**: `"Entitlement changes (create, update, delete)."` = `'Entitlement changes (create, update, delete).'` #### entitlements.kind [Section titled “entitlements.kind”](#entitlementskind) > `readonly` **kind**: `"counter"` = `'counter'` #### entitlements.labels [Section titled “entitlements.labels”](#entitlementslabels) > `readonly` **labels**: readonly \[`"action"`] #### entitlements.unit [Section titled “entitlements.unit”](#entitlementsunit) > `readonly` **unit**: `"1"` = `'1'` ### eventloop_delay_p99 [Section titled “eventloop_delay_p99”](#eventloop_delay_p99) > `readonly` **eventloop_delay_p99**: `object` #### eventloop_delay_p99.description [Section titled “eventloop_delay_p99.description”](#eventloop_delay_p99description) > `readonly` **description**: `"Event loop delay, 99th percentile over the last 30 seconds."` = `'Event loop delay, 99th percentile over the last 30 seconds.'` #### eventloop_delay_p99.kind [Section titled “eventloop_delay_p99.kind”](#eventloop_delay_p99kind) > `readonly` **kind**: `"gauge"` = `'gauge'` #### eventloop_delay_p99.labels [Section titled “eventloop_delay_p99.labels”](#eventloop_delay_p99labels) > `readonly` **labels**: readonly \[] = `[]` #### eventloop_delay_p99.unit [Section titled “eventloop_delay_p99.unit”](#eventloop_delay_p99unit) > `readonly` **unit**: `"seconds"` = `'seconds'` ### guild_events [Section titled “guild_events”](#guild_events) > `readonly` **guild_events**: `object` #### guild_events.description [Section titled “guild_events.description”](#guild_eventsdescription) > `readonly` **description**: `"Servers joined and left, and outages (unavailable, available)."` = `'Servers joined and left, and outages (unavailable, available).'` #### guild_events.kind [Section titled “guild_events.kind”](#guild_eventskind) > `readonly` **kind**: `"counter"` = `'counter'` #### guild_events.labels [Section titled “guild_events.labels”](#guild_eventslabels) > `readonly` **labels**: readonly \[`"event"`] #### guild_events.unit [Section titled “guild_events.unit”](#guild_eventsunit) > `readonly` **unit**: `"1"` = `'1'` ### guilds [Section titled “guilds”](#guilds) > `readonly` **guilds**: `object` #### guilds.description [Section titled “guilds.description”](#guildsdescription) > `readonly` **description**: `"Servers per shard."` = `'Servers per shard.'` #### guilds.kind [Section titled “guilds.kind”](#guildskind) > `readonly` **kind**: `"gauge"` = `'gauge'` #### guilds.labels [Section titled “guilds.labels”](#guildslabels) > `readonly` **labels**: readonly \[`"shard"`] #### guilds.unit [Section titled “guilds.unit”](#guildsunit) > `readonly` **unit**: `"1"` = `'1'` ### identify_remaining [Section titled “identify_remaining”](#identify_remaining) > `readonly` **identify_remaining**: `object` #### identify_remaining.description [Section titled “identify_remaining.description”](#identify_remainingdescription) > `readonly` **description**: `"Gateway sessions left in Discord's daily identify budget."` = `"Gateway sessions left in Discord's daily identify budget."` #### identify_remaining.kind [Section titled “identify_remaining.kind”](#identify_remainingkind) > `readonly` **kind**: `"gauge"` = `'gauge'` #### identify_remaining.labels [Section titled “identify_remaining.labels”](#identify_remaininglabels) > `readonly` **labels**: readonly \[] = `[]` #### identify_remaining.unit [Section titled “identify_remaining.unit”](#identify_remainingunit) > `readonly` **unit**: `"1"` = `'1'` ### interaction_errors [Section titled “interaction_errors”](#interaction_errors) > `readonly` **interaction_errors**: `object` #### interaction_errors.description [Section titled “interaction_errors.description”](#interaction_errorsdescription) > `readonly` **description**: `"Errors thrown by wrapped handlers, by error class (never the message)."` = `'Errors thrown by wrapped handlers, by error class (never the message).'` #### interaction_errors.kind [Section titled “interaction_errors.kind”](#interaction_errorskind) > `readonly` **kind**: `"counter"` = `'counter'` #### interaction_errors.labels [Section titled “interaction_errors.labels”](#interaction_errorslabels) > `readonly` **labels**: readonly \[`"command"`, `"error_class"`] #### interaction_errors.unit [Section titled “interaction_errors.unit”](#interaction_errorsunit) > `readonly` **unit**: `"1"` = `'1'` ### interaction_handler [Section titled “interaction_handler”](#interaction_handler) > `readonly` **interaction_handler**: `object` #### interaction_handler.description [Section titled “interaction_handler.description”](#interaction_handlerdescription) > `readonly` **description**: `"Time spent in a handler wrapped with lens.wrap(), or reported for a message command."` = `'Time spent in a handler wrapped with lens.wrap(), or reported for a message command.'` #### interaction_handler.kind [Section titled “interaction_handler.kind”](#interaction_handlerkind) > `readonly` **kind**: `"histogram"` = `'histogram'` #### interaction_handler.labels [Section titled “interaction_handler.labels”](#interaction_handlerlabels) > `readonly` **labels**: readonly \[`"kind"`, `"command"`] #### interaction_handler.unit [Section titled “interaction_handler.unit”](#interaction_handlerunit) > `readonly` **unit**: `"seconds"` = `'seconds'` ### interaction_response [Section titled “interaction_response”](#interaction_response) > `readonly` **interaction_response**: `object` #### interaction_response.description [Section titled “interaction_response.description”](#interaction_responsedescription) > `readonly` **description**: `"Time from Discord's interaction timestamp to the first response. Discord's deadline is 3 seconds."` = `"Time from Discord's interaction timestamp to the first response. Discord's deadline is 3 seconds."` #### interaction_response.kind [Section titled “interaction_response.kind”](#interaction_responsekind) > `readonly` **kind**: `"histogram"` = `'histogram'` #### interaction_response.labels [Section titled “interaction_response.labels”](#interaction_responselabels) > `readonly` **labels**: readonly \[`"kind"`, `"command"`] #### interaction_response.unit [Section titled “interaction_response.unit”](#interaction_responseunit) > `readonly` **unit**: `"seconds"` = `'seconds'` ### interactions [Section titled “interactions”](#interactions) > `readonly` **interactions**: `object` #### interactions.description [Section titled “interactions.description”](#interactionsdescription) > `readonly` **description**: `"Interactions handled (commands, context menus, components, modals, autocomplete) and message (prefix) commands, by outcome."` = `'Interactions handled (commands, context menus, components, modals, autocomplete) and message (prefix) commands, by outcome.'` #### interactions.kind [Section titled “interactions.kind”](#interactionskind) > `readonly` **kind**: `"counter"` = `'counter'` #### interactions.labels [Section titled “interactions.labels”](#interactionslabels) > `readonly` **labels**: readonly \[`"kind"`, `"command"`, `"outcome"`] #### interactions.unit [Section titled “interactions.unit”](#interactionsunit) > `readonly` **unit**: `"1"` = `'1'` ### memory [Section titled “memory”](#memory) > `readonly` **memory**: `object` #### memory.description [Section titled “memory.description”](#memorydescription) > `readonly` **description**: `"Process memory (rss, heap_used)."` = `'Process memory (rss, heap_used).'` #### memory.kind [Section titled “memory.kind”](#memorykind) > `readonly` **kind**: `"gauge"` = `'gauge'` #### memory.labels [Section titled “memory.labels”](#memorylabels) > `readonly` **labels**: readonly \[`"type"`] #### memory.unit [Section titled “memory.unit”](#memoryunit) > `readonly` **unit**: `"bytes"` = `'bytes'` ### ratelimits [Section titled “ratelimits”](#ratelimits) > `readonly` **ratelimits**: `object` #### ratelimits.description [Section titled “ratelimits.description”](#ratelimitsdescription) > `readonly` **description**: `"Requests held back for a rate limit, by scope (user, global or shared)."` = `'Requests held back for a rate limit, by scope (user, global or shared).'` #### ratelimits.kind [Section titled “ratelimits.kind”](#ratelimitskind) > `readonly` **kind**: `"counter"` = `'counter'` #### ratelimits.labels [Section titled “ratelimits.labels”](#ratelimitslabels) > `readonly` **labels**: readonly \[`"scope"`] #### ratelimits.unit [Section titled “ratelimits.unit”](#ratelimitsunit) > `readonly` **unit**: `"1"` = `'1'` ### rest_invalid_requests [Section titled “rest_invalid_requests”](#rest_invalid_requests) > `readonly` **rest_invalid_requests**: `object` #### rest_invalid_requests.description [Section titled “rest_invalid_requests.description”](#rest_invalid_requestsdescription) > `readonly` **description**: `"Responses that count towards Discord's invalid-request limit (10,000 per 10 minutes per IP)."` = `"Responses that count towards Discord's invalid-request limit (10,000 per 10 minutes per IP)."` #### rest_invalid_requests.kind [Section titled “rest_invalid_requests.kind”](#rest_invalid_requestskind) > `readonly` **kind**: `"counter"` = `'counter'` #### rest_invalid_requests.labels [Section titled “rest_invalid_requests.labels”](#rest_invalid_requestslabels) > `readonly` **labels**: readonly \[`"status"`] #### rest_invalid_requests.unit [Section titled “rest_invalid_requests.unit”](#rest_invalid_requestsunit) > `readonly` **unit**: `"1"` = `'1'` ### rest_requests [Section titled “rest_requests”](#rest_requests) > `readonly` **rest_requests**: `object` #### rest_requests.description [Section titled “rest_requests.description”](#rest_requestsdescription) > `readonly` **description**: `"REST requests to Discord, by method, bucketed route and status."` = `'REST requests to Discord, by method, bucketed route and status.'` #### rest_requests.kind [Section titled “rest_requests.kind”](#rest_requestskind) > `readonly` **kind**: `"counter"` = `'counter'` #### rest_requests.labels [Section titled “rest_requests.labels”](#rest_requestslabels) > `readonly` **labels**: readonly \[`"method"`, `"route"`, `"status"`] #### rest_requests.unit [Section titled “rest_requests.unit”](#rest_requestsunit) > `readonly` **unit**: `"1"` = `'1'` ### shard_events [Section titled “shard_events”](#shard_events) > `readonly` **shard_events**: `object` #### shard_events.description [Section titled “shard_events.description”](#shard_eventsdescription) > `readonly` **description**: `"Shard state changes (ready, resumed, reconnecting, disconnected, error, invalidated)."` = `'Shard state changes (ready, resumed, reconnecting, disconnected, error, invalidated).'` #### shard_events.kind [Section titled “shard_events.kind”](#shard_eventskind) > `readonly` **kind**: `"counter"` = `'counter'` #### shard_events.labels [Section titled “shard_events.labels”](#shard_eventslabels) > `readonly` **labels**: readonly \[`"shard"`, `"state"`] #### shard_events.unit [Section titled “shard_events.unit”](#shard_eventsunit) > `readonly` **unit**: `"1"` = `'1'` ### shard_ping [Section titled “shard_ping”](#shard_ping) > `readonly` **shard_ping**: `object` #### shard_ping.description [Section titled “shard_ping.description”](#shard_pingdescription) > `readonly` **description**: `"Gateway heartbeat latency per shard."` = `'Gateway heartbeat latency per shard.'` #### shard_ping.kind [Section titled “shard_ping.kind”](#shard_pingkind) > `readonly` **kind**: `"gauge"` = `'gauge'` #### shard_ping.labels [Section titled “shard_ping.labels”](#shard_pinglabels) > `readonly` **labels**: readonly \[`"shard"`] #### shard_ping.unit [Section titled “shard_ping.unit”](#shard_pingunit) > `readonly` **unit**: `"seconds"` = `'seconds'` # HASH_BYTES > `const` **HASH_BYTES**: `16` = `16` Defined in: [packages/core/src/hash.ts:23](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L23) # HASH_VERSION > `const` **HASH_VERSION**: `"h1"` = `'h1'` Defined in: [packages/core/src/hash.ts:21](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/hash.ts#L21) # MAX_CUSTOM_ID_LENGTH > `const` **MAX_CUSTOM_ID_LENGTH**: `100` = `100` Defined in: [packages/core/src/normalise.ts:4](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/normalise.ts#L4) # MAX_CUSTOM_PROPS_BYTES > `const` **MAX_CUSTOM_PROPS_BYTES**: `2048` = `2048` Defined in: [packages/core/src/custom-events.ts:32](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/custom-events.ts#L32) # MAX_MS > `const` **MAX_MS**: `60000` = `60_000` Defined in: [packages/core/src/histogram.ts:9](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/histogram.ts#L9) Larger durations land in the last bucket. # PRIORITIES > `const` **PRIORITIES**: `4` = `4` Defined in: [packages/core/src/queue.ts:8](https://github.com/Kkkermit/Shardlens/blob/main/packages/core/src/queue.ts#L8) # createPrivacyCommand > **createPrivacyCommand**(`lens`, `options?`): [`PrivacyCommand`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/privacycommand/) Defined in: [packages/discordjs/src/privacy-command.ts:31](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/privacy-command.ts#L31) A ready-made `/privacy` command: `info` explains what is collected, `optout` and `optin` stop and resume collection for the user, `erase` deletes what `forgetUser()` can reach of them and opts them out. Replies are ephemeral. Opt-outs live in memory: persist them with `onOptOutChange` and pass them back with `optedOut`. ## Parameters [Section titled “Parameters”](#parameters) ### lens [Section titled “lens”](#lens) [`Shardlens`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/) ### options? [Section titled “options?”](#options) [`PrivacyCommandOptions`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/privacycommandoptions/) = `{}` ## Returns [Section titled “Returns”](#returns) [`PrivacyCommand`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/privacycommand/) # createShardlens > **createShardlens**(`client`, `options`): [`Shardlens`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/) Defined in: [packages/discordjs/src/index.ts:166](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L166) Attaches Shardlens to a discord.js client. Call it before `client.login()`. Only the `Guilds` intent is needed. The SDK never throws into your bot: every failure is caught and counted. ## Parameters [Section titled “Parameters”](#parameters) ### client [Section titled “client”](#client) `Client` ### options [Section titled “options”](#options) [`ShardlensOptions`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensoptions/) ## Returns [Section titled “Returns”](#returns) [`Shardlens`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/) # normaliseRoute > **normaliseRoute**(`route`): `string` Defined in: [packages/discordjs/src/util.ts:56](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/util.ts#L56) Normalises a REST route before it is stored or used as a metric label, so it holds only route words and placeholders: snowflakes become `:id` (including 20-digit IDs that `@discordjs/rest` does not template), invite and template codes `:code`, webhook and interaction tokens `:token` and any other value `:param`. The query string is dropped, an encoded `@` is written plainly (`/guilds/:id/members/@me`), and the result is capped at 200 characters. ## Parameters [Section titled “Parameters”](#parameters) ### route [Section titled “route”](#route) `string` ## Returns [Section titled “Returns”](#returns) `string` # CustomEvents Defined in: packages/core/dist/index.d.ts:386 Register your custom events here for typed `track()` calls. Name the Shardlens package your bot installs (`@shardlens/discordjs` or `@shardlens/http`): with pnpm, a bot can’t see `@shardlens/core` itself. ## Example [Section titled “Example”](#example) ```ts declare module '@shardlens/discordjs' { interface CustomEvents { ticket_opened: { category: 'billing' | 'support' }; } } lens.track('ticket_opened', { category: 'billing' }); ``` # HandlerResult Defined in: [packages/discordjs/src/index.ts:80](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L80) How a handler went, for [Shardlens.handlerFinished](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#handlerfinished). ## Properties [Section titled “Properties”](#properties) ### durationMs? [Section titled “durationMs?”](#durationms) > `optional` **durationMs?**: `number` Defined in: [packages/discordjs/src/index.ts:82](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L82) How long the handler ran, in milliseconds. Measured from `handlerStarted()` when left out. *** ### error? [Section titled “error?”](#error) > `optional` **error?**: `unknown` Defined in: [packages/discordjs/src/index.ts:84](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L84) What the handler threw, if anything. Only its class name and Discord error code are recorded. # MessageCommandInfo Defined in: [packages/discordjs/src/message-commands.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L11) A command that ran from a message, as your bot’s own parser understood it. ## Extended by [Section titled “Extended by”](#extended-by) * [`MessageCommandRun`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandrun/) ## Properties [Section titled “Properties”](#properties) ### command [Section titled “command”](#command) > **command**: `string` Defined in: [packages/discordjs/src/message-commands.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L13) The command’s name as your bot defines it, after aliases are resolved (`ban`, not what was typed). 1–32 characters. *** ### group? [Section titled “group?”](#group) > `optional` **group?**: `string` Defined in: [packages/discordjs/src/message-commands.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L15) Subcommand group, if the command has one. *** ### options? [Section titled “options?”](#options) > `optional` **options?**: readonly `string`\[] Defined in: [packages/discordjs/src/message-commands.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L19) Names of the arguments the user gave. *** ### optionValues? [Section titled “optionValues?”](#optionvalues) > `optional` **optionValues?**: `Readonly`<`Record`<`string`, `string` | `number` | `boolean`>> Defined in: [packages/discordjs/src/message-commands.ts:24](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L24) Argument values. Only names listed in `captureOptionValues` are kept, never a value holding a Discord ID (pass a mentioned user or channel as an argument name, not a value); strings are cut to 100 characters. *** ### sub? [Section titled “sub?”](#sub) > `optional` **sub?**: `string` Defined in: [packages/discordjs/src/message-commands.ts:17](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L17) Subcommand, if the command has one. # MessageCommandRun Defined in: [packages/discordjs/src/message-commands.ts:28](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L28) How a message command went. ## Extends [Section titled “Extends”](#extends) * [`MessageCommandInfo`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/) ## Properties [Section titled “Properties”](#properties) ### command [Section titled “command”](#command) > **command**: `string` Defined in: [packages/discordjs/src/message-commands.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L13) The command’s name as your bot defines it, after aliases are resolved (`ban`, not what was typed). 1–32 characters. #### Inherited from [Section titled “Inherited from”](#inherited-from) [`MessageCommandInfo`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/).[`command`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/#command) *** ### durationMs? [Section titled “durationMs?”](#durationms) > `optional` **durationMs?**: `number` Defined in: [packages/discordjs/src/message-commands.ts:30](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L30) How long the handler took, in milliseconds. *** ### error? [Section titled “error?”](#error) > `optional` **error?**: `unknown` Defined in: [packages/discordjs/src/message-commands.ts:32](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L32) What the handler threw, if anything. Only its class name and Discord error code are recorded. *** ### failed? [Section titled “failed?”](#failed) > `optional` **failed?**: `boolean` Defined in: [packages/discordjs/src/message-commands.ts:34](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L34) The command failed, but your bot caught the error itself. Implied when `error` is set. *** ### group? [Section titled “group?”](#group) > `optional` **group?**: `string` Defined in: [packages/discordjs/src/message-commands.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L15) Subcommand group, if the command has one. #### Inherited from [Section titled “Inherited from”](#inherited-from-1) [`MessageCommandInfo`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/).[`group`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/#group) *** ### options? [Section titled “options?”](#options) > `optional` **options?**: readonly `string`\[] Defined in: [packages/discordjs/src/message-commands.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L19) Names of the arguments the user gave. #### Inherited from [Section titled “Inherited from”](#inherited-from-2) [`MessageCommandInfo`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/).[`options`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/#options) *** ### optionValues? [Section titled “optionValues?”](#optionvalues) > `optional` **optionValues?**: `Readonly`<`Record`<`string`, `string` | `number` | `boolean`>> Defined in: [packages/discordjs/src/message-commands.ts:24](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L24) Argument values. Only names listed in `captureOptionValues` are kept, never a value holding a Discord ID (pass a mentioned user or channel as an argument name, not a value); strings are cut to 100 characters. #### Inherited from [Section titled “Inherited from”](#inherited-from-3) [`MessageCommandInfo`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/).[`optionValues`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/#optionvalues) *** ### sub? [Section titled “sub?”](#sub) > `optional` **sub?**: `string` Defined in: [packages/discordjs/src/message-commands.ts:17](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/message-commands.ts#L17) Subcommand, if the command has one. #### Inherited from [Section titled “Inherited from”](#inherited-from-4) [`MessageCommandInfo`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/).[`sub`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/#sub) # PrivacyCommand Defined in: [packages/discordjs/src/privacy-command.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/privacy-command.ts#L19) What [createPrivacyCommand](/Shardlens/reference/sdk/shardlens/discordjs/functions/createprivacycommand/) returns. ## Properties [Section titled “Properties”](#properties) ### data [Section titled “data”](#data) > **data**: `RESTPostAPIChatInputApplicationCommandsJSONBody` Defined in: [packages/discordjs/src/privacy-command.ts:21](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/privacy-command.ts#L21) Command definition to register with Discord (`rest.put(Routes.applicationCommands(id), { body: [data] })`). ## Methods [Section titled “Methods”](#methods) ### handle() [Section titled “handle()”](#handle) > **handle**(`interaction`): `Promise`<`boolean`> Defined in: [packages/discordjs/src/privacy-command.ts:23](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/privacy-command.ts#L23) Handles the command. Returns `false` for interactions that aren’t this command. Never throws. #### Parameters [Section titled “Parameters”](#parameters) ##### interaction [Section titled “interaction”](#interaction) `ChatInputCommandInteraction` #### Returns [Section titled “Returns”](#returns) `Promise`<`boolean`> # PrivacyCommandOptions Defined in: [packages/discordjs/src/privacy-command.ts:11](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/privacy-command.ts#L11) Options for [createPrivacyCommand](/Shardlens/reference/sdk/shardlens/discordjs/functions/createprivacycommand/). ## Properties [Section titled “Properties”](#properties) ### name? [Section titled “name?”](#name) > `optional` **name?**: `string` Defined in: [packages/discordjs/src/privacy-command.ts:13](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/privacy-command.ts#L13) The command’s name. Default `privacy`. *** ### policyUrl? [Section titled “policyUrl?”](#policyurl) > `optional` **policyUrl?**: `string` Defined in: [packages/discordjs/src/privacy-command.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/privacy-command.ts#L15) Link to your bot’s privacy policy, shown in `/privacy info`. # Shardlens Defined in: [packages/discordjs/src/index.ts:97](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L97) What [createShardlens](/Shardlens/reference/sdk/shardlens/discordjs/functions/createshardlens/) returns. Its methods never throw; wrapped handlers re-throw only their own errors. ## Properties [Section titled “Properties”](#properties) ### client [Section titled “client”](#client) > `readonly` **client**: `ShardlensClient` Defined in: [packages/discordjs/src/index.ts:159](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L159) The underlying transport from `@shardlens/core`, for adapters and tools built on this one. ## Methods [Section titled “Methods”](#methods) ### flush() [Section titled “flush()”](#flush) > **flush**(): `Promise`<`void`> Defined in: [packages/discordjs/src/index.ts:150](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L150) Sends what is queued now instead of at the next interval. Never throws. #### Returns [Section titled “Returns”](#returns) `Promise`<`void`> *** ### forgetUser() [Section titled “forgetUser()”](#forgetuser) > **forgetUser**(`userId`): `Promise`<{ `erased`: `number`; } | `undefined`> Defined in: [packages/discordjs/src/index.ts:143](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L143) Deletes what the collector stored about a user (right to erasure): in privacy mode, the rows under the hashes this bot can still compute, which are those of the current salt period and the previous one; in audit mode, every period whose salt still exists. Does not opt them out of future collection; call [Shardlens.optOut](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#optout) as well if they asked for that. Never throws. #### Parameters [Section titled “Parameters”](#parameters) ##### userId [Section titled “userId”](#userid) `string` #### Returns [Section titled “Returns”](#returns-1) `Promise`<{ `erased`: `number`; } | `undefined`> *** ### handlerFinished() [Section titled “handlerFinished()”](#handlerfinished) > **handlerFinished**(`interaction`, `result?`): `void` Defined in: [packages/discordjs/src/index.ts:116](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L116) Call when a handler started with [Shardlens.handlerStarted](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#handlerstarted) has finished or thrown. #### Parameters [Section titled “Parameters”](#parameters-1) ##### interaction [Section titled “interaction”](#interaction) `BaseInteraction` ##### result? [Section titled “result?”](#result) [`HandlerResult`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/handlerresult/) #### Returns [Section titled “Returns”](#returns-2) `void` *** ### handlerStarted() [Section titled “handlerStarted()”](#handlerstarted) > **handlerStarted**(`interaction`): `void` Defined in: [packages/discordjs/src/index.ts:114](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L114) For frameworks that run handlers themselves and announce it (Sapphire’s `chatInputCommandRun`, for example): call when the handler starts. With [Shardlens.handlerFinished](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#handlerfinished) it records what [Shardlens.wrap](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#wrap) would. #### Parameters [Section titled “Parameters”](#parameters-2) ##### interaction [Section titled “interaction”](#interaction-1) `BaseInteraction` #### Returns [Section titled “Returns”](#returns-3) `void` *** ### isOptedOut() [Section titled “isOptedOut()”](#isoptedout) > **isOptedOut**(`userId`): `boolean` Defined in: [packages/discordjs/src/index.ts:136](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L136) Whether [Shardlens.optOut](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#optout) (or the `optedOut` option) covers this user in this process. #### Parameters [Section titled “Parameters”](#parameters-3) ##### userId [Section titled “userId”](#userid-1) `string` #### Returns [Section titled “Returns”](#returns-4) `boolean` *** ### on() [Section titled “on()”](#on) > **on**(`event`, `listener`): () => `void` Defined in: [packages/discordjs/src/index.ts:148](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L148) Listens for failures the SDK caught and counted, named by where they happened (`'flush'`, `'interactionCreate'`, `'onOptOutChange'`…). Returns a function that removes the listener. #### Parameters [Section titled “Parameters”](#parameters-4) ##### event [Section titled “event”](#event) `"error"` ##### listener [Section titled “listener”](#listener) (`name`, `error`) => `void` #### Returns [Section titled “Returns”](#returns-5) () => `void` *** ### optIn() [Section titled “optIn()”](#optin) > **optIn**(`userId`): `void` Defined in: [packages/discordjs/src/index.ts:134](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L134) Reverses [Shardlens.optOut](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#optout). #### Parameters [Section titled “Parameters”](#parameters-5) ##### userId [Section titled “userId”](#userid-2) `string` #### Returns [Section titled “Returns”](#returns-6) `void` *** ### optOut() [Section titled “optOut()”](#optout) > **optOut**(`userId`): `void` Defined in: [packages/discordjs/src/index.ts:132](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L132) Stops recording a user’s interactions in this process (for example from a `/privacy optout` command). #### Parameters [Section titled “Parameters”](#parameters-6) ##### userId [Section titled “userId”](#userid-3) `string` #### Returns [Section titled “Returns”](#returns-7) `void` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(`options?`): `Promise`<`void`> Defined in: [packages/discordjs/src/index.ts:155](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L155) Removes all hooks and flushes, giving up after `timeoutMs` (default 2,000). A second call, such as SIGTERM from a shard manager after SIGINT from the terminal, waits for the same flush. The SDK never handles signals. #### Parameters [Section titled “Parameters”](#parameters-7) ##### options? [Section titled “options?”](#options) ###### timeoutMs? [Section titled “timeoutMs?”](#timeoutms) `number` #### Returns [Section titled “Returns”](#returns-8) `Promise`<`void`> *** ### stats() [Section titled “stats()”](#stats) > **stats**(): [`ShardlensStats`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensstats/) Defined in: [packages/discordjs/src/index.ts:157](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L157) Queue depth, drops by reason, failed sends and caught errors, for your own health checks. #### Returns [Section titled “Returns”](#returns-9) [`ShardlensStats`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensstats/) *** ### track() [Section titled “track()”](#track) > **track**<`N`>(`name`, `props?`, `context?`): `void` Defined in: [packages/discordjs/src/index.ts:102](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L102) Records a custom event. Names are lower snake case; properties are limited to 2 KB of strings, numbers, booleans and nulls. Invalid events are dropped and counted, never thrown. #### Type Parameters [Section titled “Type Parameters”](#type-parameters) ##### N [Section titled “N”](#n) `N` *extends* `string` #### Parameters [Section titled “Parameters”](#parameters-8) ##### name [Section titled “name”](#name) `N` ##### props? [Section titled “props?”](#props) `CustomEventProps`<`N`> ##### context? [Section titled “context?”](#context) [`TrackContext`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/trackcontext/) #### Returns [Section titled “Returns”](#returns-10) `void` *** ### trackMessageCommand() [Section titled “trackMessageCommand()”](#trackmessagecommand) > **trackMessageCommand**(`message`, `run`): `void` Defined in: [packages/discordjs/src/index.ts:122](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L122) Records a command run from a message, such as a prefix command (`!ban @user`), after your bot’s parser matched it. Pass the command’s own name, not what was typed: message content is never read. Counted with interactions on the dashboard. Invalid runs are dropped and counted, never thrown. #### Parameters [Section titled “Parameters”](#parameters-9) ##### message [Section titled “message”](#message) `Message` ##### run [Section titled “run”](#run) [`MessageCommandRun`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandrun/) #### Returns [Section titled “Returns”](#returns-11) `void` *** ### wrap() [Section titled “wrap()”](#wrap) > **wrap**<`A`, `R`>(`handler`): (…`args`) => `Promise`<`Awaited`<`R`>> Defined in: [packages/discordjs/src/index.ts:107](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L107) Wraps an interaction handler to record its duration and failures. The handler’s errors are re-thrown unchanged, so your own error handling still runs. #### Type Parameters [Section titled “Type Parameters”](#type-parameters-1) ##### A [Section titled “A”](#a) `A` *extends* \[`BaseInteraction`<`CacheType`>, `...unknown[]`] ##### R [Section titled “R”](#r) `R` #### Parameters [Section titled “Parameters”](#parameters-10) ##### handler [Section titled “handler”](#handler) (…`args`) => `R` | `Promise`<`R`> #### Returns [Section titled “Returns”](#returns-12) (…`args`) => `Promise`<`Awaited`<`R`>> *** ### wrapMessageCommand() [Section titled “wrapMessageCommand()”](#wrapmessagecommand) > **wrapMessageCommand**<`A`, `R`>(`command`, `handler`): (…`args`) => `Promise`<`Awaited`<`R`>> Defined in: [packages/discordjs/src/index.ts:127](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L127) Wraps a message command handler to record its duration and failures, like [Shardlens.wrap](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/#wrap) does for interactions. The handler’s errors are re-thrown unchanged. #### Type Parameters [Section titled “Type Parameters”](#type-parameters-2) ##### A [Section titled “A”](#a-1) `A` *extends* \[`Message`<`boolean`>, `...unknown[]`] ##### R [Section titled “R”](#r-1) `R` #### Parameters [Section titled “Parameters”](#parameters-11) ##### command [Section titled “command”](#command) `string` | [`MessageCommandInfo`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/) ##### handler [Section titled “handler”](#handler-1) (…`args`) => `R` | `Promise`<`R`> #### Returns [Section titled “Returns”](#returns-13) (…`args`) => `Promise`<`Awaited`<`R`>> # ShardlensExporter Defined in: packages/core/dist/index.d.ts:25 Receives every event the SDK records, in-process and before sampling. Events never carry a user. Implementations must not label metrics by user or server ID, do I/O in `observe`, or throw. ## Extended by [Section titled “Extended by”](#extended-by) * [`PrometheusExporter`](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/prometheusexporter/) ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > `readonly` **name**: `string` Defined in: packages/core/dist/index.d.ts:27 Short name, used when counting errors (`exporter:`). ## Methods [Section titled “Methods”](#methods) ### observe() [Section titled “observe()”](#observe) > **observe**(`event`): `void` Defined in: packages/core/dist/index.d.ts:28 #### Parameters [Section titled “Parameters”](#parameters) ##### event [Section titled “event”](#event) `WireEvent` #### Returns [Section titled “Returns”](#returns) `void` *** ### shutdown()? [Section titled “shutdown()?”](#shutdown) > `optional` **shutdown**(): `void` | `Promise`<`void`> Defined in: packages/core/dist/index.d.ts:29 #### Returns [Section titled “Returns”](#returns-1) `void` | `Promise`<`void`> # ShardlensOptions Defined in: [packages/discordjs/src/options.ts:7](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L7) Options for `createShardlens(client, options)`. Every one is optional. ## Properties [Section titled “Properties”](#properties) ### apiKey? [Section titled “apiKey?”](#apikey) > `optional` **apiKey?**: `string` Defined in: [packages/discordjs/src/options.ts:14](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L14) Ingest-only API key (`slk_ingest_…`). *** ### auditIncludeProfile? [Section titled “auditIncludeProfile?”](#auditincludeprofile) > `optional` **auditIncludeProfile?**: `boolean` Defined in: [packages/discordjs/src/options.ts:30](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L30) 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. *** ### captureOptionValues? [Section titled “captureOptionValues?”](#captureoptionvalues) > `optional` **captureOptionValues?**: readonly `string`\[] Defined in: [packages/discordjs/src/options.ts:49](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L49) 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. *** ### disable? [Section titled “disable?”](#disable) > `optional` **disable?**: readonly [`MetricGroup`](/Shardlens/reference/sdk/shardlens/discordjs/type-aliases/metricgroup/)\[] Defined in: [packages/discordjs/src/options.ts:64](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L64) Turn off whole metric groups. `'interactions'` also turns off message (prefix) commands. *** ### dryRun? [Section titled “dryRun?”](#dryrun) > `optional` **dryRun?**: `boolean` Defined in: [packages/discordjs/src/options.ts:62](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L62) Print events to the console instead of sending them. *** ### endpoint? [Section titled “endpoint?”](#endpoint) > `optional` **endpoint?**: `string` Defined in: [packages/discordjs/src/options.ts:12](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L12) 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. *** ### environment? [Section titled “environment?”](#environment) > `optional` **environment?**: `string` Defined in: [packages/discordjs/src/options.ts:58](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L58) Separates staging from production. Default `'production'`. *** ### exporters? [Section titled “exporters?”](#exporters) > `optional` **exporters?**: readonly [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/)\[] Defined in: [packages/discordjs/src/options.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L19) 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. *** ### fetch? [Section titled “fetch?”](#fetch) > `optional` **fetch?**: {(`input`, `init?`): `Promise`<`Response`>; (`input`, `init?`): `Promise`<`Response`>; } Defined in: [packages/discordjs/src/options.ts:92](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L92) Override `fetch` (tests, proxies). #### Call Signature [Section titled “Call Signature”](#call-signature) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters) ###### input [Section titled “input”](#input) `URL` | `RequestInfo` ###### init? [Section titled “init?”](#init) `RequestInit` ##### Returns [Section titled “Returns”](#returns) `Promise`<`Response`> #### Call Signature [Section titled “Call Signature”](#call-signature-1) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters-1) ###### input [Section titled “input”](#input-1) `string` | `URL` | `Request` ###### init? [Section titled “init?”](#init-1) `RequestInit` ##### Returns [Section titled “Returns”](#returns-1) `Promise`<`Response`> *** ### flushIntervalMs? [Section titled “flushIntervalMs?”](#flushintervalms) > `optional` **flushIntervalMs?**: `number` Defined in: [packages/discordjs/src/options.ts:41](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L41) Flush interval. Default 5,000 ms. *** ### logger? [Section titled “logger?”](#logger) > `optional` **logger?**: `Logger` Defined in: [packages/discordjs/src/options.ts:66](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L66) Where SDK warnings go. Default `console`. *** ### maxBatchSize? [Section titled “maxBatchSize?”](#maxbatchsize) > `optional` **maxBatchSize?**: `number` Defined in: [packages/discordjs/src/options.ts:43](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L43) Events per batch (max 499 plus one health event). Default 499. *** ### maxQueueSize? [Section titled “maxQueueSize?”](#maxqueuesize) > `optional` **maxQueueSize?**: `number` Defined in: [packages/discordjs/src/options.ts:39](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L39) Memory ceiling, in events. Default 10,000. *** ### mode? [Section titled “mode?”](#mode) > `optional` **mode?**: `"privacy"` | `"audit"` Defined in: [packages/discordjs/src/options.ts:25](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L25) 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. *** ### normaliseCustomId? [Section titled “normaliseCustomId?”](#normalisecustomid) > `optional` **normaliseCustomId?**: (`customId`) => `string` Defined in: [packages/discordjs/src/options.ts:51](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L51) Replaces the default custom-ID normaliser (numbers and IDs become `*`). #### Parameters [Section titled “Parameters”](#parameters-2) ##### customId [Section titled “customId”](#customid) `string` #### Returns [Section titled “Returns”](#returns-2) `string` *** ### onOptOutChange? [Section titled “onOptOutChange?”](#onoptoutchange) > `optional` **onOptOutChange?**: (`userId`, `optedOut`) => `void` Defined in: [packages/discordjs/src/options.ts:76](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L76) 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. #### Parameters [Section titled “Parameters”](#parameters-3) ##### userId [Section titled “userId”](#userid) `string` ##### optedOut [Section titled “optedOut”](#optedout) `boolean` #### Returns [Section titled “Returns”](#returns-3) `void` *** ### optedOut? [Section titled “optedOut?”](#optedout-1) > `optional` **optedOut?**: `Iterable`<`string` | `bigint`, `any`, `any`> Defined in: [packages/discordjs/src/options.ts:71](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L71) 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. *** ### refreshGuildCounts? [Section titled “refreshGuildCounts?”](#refreshguildcounts) > `optional` **refreshGuildCounts?**: `boolean` Defined in: [packages/discordjs/src/options.ts:90](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L90) 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`. *** ### release? [Section titled “release?”](#release) > `optional` **release?**: `string` Defined in: [packages/discordjs/src/options.ts:60](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L60) Your bot’s version, to compare releases. *** ### ~~saltPeriod?~~ [Section titled “saltPeriod?”](#saltperiod) > `optional` **saltPeriod?**: `SaltPeriod` Defined in: [packages/discordjs/src/options.ts:37](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L37) 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. Deprecated Set the salt period on the collector. *** ### sampleRate? [Section titled “sampleRate?”](#samplerate) > `optional` **sampleRate?**: `Readonly`<`Record`<`string`, `number`>> Defined in: [packages/discordjs/src/options.ts:56](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L56) 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. *** ### spool? [Section titled “spool?”](#spool) > `optional` **spool?**: `object` Defined in: [packages/discordjs/src/options.ts:84](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L84) 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). #### dir [Section titled “dir”](#dir) > **dir**: `string` #### maxBytes? [Section titled “maxBytes?”](#maxbytes) > `optional` **maxBytes?**: `number` # ShardlensStats Defined in: [packages/discordjs/src/index.ts:91](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L91) SDK health, including interactions still waiting for a response. `dropped.spool_evicted` counts spooled events the disk spool dropped at its size cap, which `spooled` still includes. ## Extends [Section titled “Extends”](#extends) * `ClientStats` ## Properties [Section titled “Properties”](#properties) ### dropped [Section titled “dropped”](#dropped) > **dropped**: `Record`<`string`, `number`> Defined in: packages/core/dist/index.d.ts:304 #### Inherited from [Section titled “Inherited from”](#inherited-from) `ClientStats.dropped` *** ### failedFlushes [Section titled “failedFlushes”](#failedflushes) > **failedFlushes**: `number` Defined in: packages/core/dist/index.d.ts:305 #### Inherited from [Section titled “Inherited from”](#inherited-from-1) `ClientStats.failedFlushes` *** ### internalErrors [Section titled “internalErrors”](#internalerrors) > **internalErrors**: `Record`<`string`, `number`> Defined in: packages/core/dist/index.d.ts:306 #### Inherited from [Section titled “Inherited from”](#inherited-from-2) `ClientStats.internalErrors` *** ### mode [Section titled “mode”](#mode) > **mode**: `DataMode` | `undefined` Defined in: packages/core/dist/index.d.ts:308 #### Inherited from [Section titled “Inherited from”](#inherited-from-3) `ClientStats.mode` *** ### pendingInteractions [Section titled “pendingInteractions”](#pendinginteractions) > **pendingInteractions**: `number` Defined in: [packages/discordjs/src/index.ts:93](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L93) Interactions waiting for their first response or their wrapped handler, sent after 10 seconds at most. *** ### pendingSalt [Section titled “pendingSalt”](#pendingsalt) > **pendingSalt**: `number` Defined in: packages/core/dist/index.d.ts:303 #### Inherited from [Section titled “Inherited from”](#inherited-from-4) `ClientStats.pendingSalt` *** ### queueDepth [Section titled “queueDepth”](#queuedepth) > **queueDepth**: `number` Defined in: packages/core/dist/index.d.ts:302 #### Inherited from [Section titled “Inherited from”](#inherited-from-5) `ClientStats.queueDepth` *** ### ready [Section titled “ready”](#ready) > **ready**: `boolean` Defined in: packages/core/dist/index.d.ts:307 #### Inherited from [Section titled “Inherited from”](#inherited-from-6) `ClientStats.ready` *** ### replayed [Section titled “replayed”](#replayed) > **replayed**: `number` Defined in: packages/core/dist/index.d.ts:312 Spooled events the collector has since accepted. #### Inherited from [Section titled “Inherited from”](#inherited-from-7) `ClientStats.replayed` *** ### spooled [Section titled “spooled”](#spooled) > **spooled**: `number` Defined in: packages/core/dist/index.d.ts:310 Events written to the spool during this process’s lifetime (0 without a spool). #### Inherited from [Section titled “Inherited from”](#inherited-from-8) `ClientStats.spooled` # TrackContext Defined in: [packages/discordjs/src/index.ts:72](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L72) Optional context for a custom event. The user ID is hashed in-process before it is sent. ## Properties [Section titled “Properties”](#properties) ### guildId? [Section titled “guildId?”](#guildid) > `optional` **guildId?**: `string` | `null` Defined in: [packages/discordjs/src/index.ts:76](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L76) The server it happened in, if any. *** ### userId? [Section titled “userId?”](#userid) > `optional` **userId?**: `string` Defined in: [packages/discordjs/src/index.ts:74](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/index.ts#L74) Who did it. Hashed in your bot, so the event counts towards unique users and funnels. # @shardlens/discordjs `@shardlens/discordjs`: privacy-first product analytics and bot health for discord.js, through public hooks only. ## Interfaces [Section titled “Interfaces”](#interfaces) * [CustomEvents](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/customevents/) * [HandlerResult](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/handlerresult/) * [MessageCommandInfo](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandinfo/) * [MessageCommandRun](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/messagecommandrun/) * [PrivacyCommand](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/privacycommand/) * [PrivacyCommandOptions](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/privacycommandoptions/) * [Shardlens](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlens/) * [ShardlensExporter](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/) * [ShardlensOptions](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensoptions/) * [ShardlensStats](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensstats/) * [TrackContext](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/trackcontext/) ## Type Aliases [Section titled “Type Aliases”](#type-aliases) * [MetricGroup](/Shardlens/reference/sdk/shardlens/discordjs/type-aliases/metricgroup/) ## Functions [Section titled “Functions”](#functions) * [createPrivacyCommand](/Shardlens/reference/sdk/shardlens/discordjs/functions/createprivacycommand/) * [createShardlens](/Shardlens/reference/sdk/shardlens/discordjs/functions/createshardlens/) * [normaliseRoute](/Shardlens/reference/sdk/shardlens/discordjs/functions/normaliseroute/) # MetricGroup > **MetricGroup** = `"interactions"` | `"guilds"` | `"rest"` | `"gateway"` | `"process"` | `"premium"` | `"app"` Defined in: [packages/discordjs/src/options.ts:4](https://github.com/Kkkermit/Shardlens/blob/main/packages/discordjs/src/options.ts#L4) Metric groups that can be switched off with [ShardlensOptions.disable](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensoptions/#disable). # openTelemetryExporter > **openTelemetryExporter**(`options?`): [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/) Defined in: [packages/exporter-otel/src/index.ts:82](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-otel/src/index.ts#L82) Creates the exporter. Pass it to `createShardlens(client, { exporters: [it] })`. ## Parameters [Section titled “Parameters”](#parameters) ### options? [Section titled “options?”](#options) [`OpenTelemetryExporterOptions`](/Shardlens/reference/sdk/shardlens/exporter-otel/interfaces/opentelemetryexporteroptions/) = `{}` ## Returns [Section titled “Returns”](#returns) [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/) # OpenTelemetryExporterOptions Defined in: [packages/exporter-otel/src/index.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-otel/src/index.ts#L27) Options for [openTelemetryExporter](/Shardlens/reference/sdk/shardlens/exporter-otel/functions/opentelemetryexporter/). ## Properties [Section titled “Properties”](#properties) ### buckets? [Section titled “buckets?”](#buckets) > `optional` **buckets?**: readonly `number`\[] Defined in: [packages/exporter-otel/src/index.ts:36](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-otel/src/index.ts#L36) Explicit bucket boundaries, in seconds, advised for the response-time and handler histograms. *** ### meter? [Section titled “meter?”](#meter) > `optional` **meter?**: `Meter` Defined in: [packages/exporter-otel/src/index.ts:32](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-otel/src/index.ts#L32) Meter to create instruments on. Default: a `@shardlens/exporter-otel` meter from the global MeterProvider, also when your OpenTelemetry SDK registers it after the exporter was created. *** ### prefix? [Section titled “prefix?”](#prefix) > `optional` **prefix?**: `string` Defined in: [packages/exporter-otel/src/index.ts:34](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-otel/src/index.ts#L34) Prefix for every instrument name. Default `shardlens.`. # @shardlens/exporter-otel `@shardlens/exporter-otel`: Shardlens bot-health metrics through the OpenTelemetry metrics API, so they go wherever your MeterProvider sends them (OTLP, Prometheus, a vendor). Works with or without a Shardlens collector. Metrics never carry a user or server attribute. ## Interfaces [Section titled “Interfaces”](#interfaces) * [OpenTelemetryExporterOptions](/Shardlens/reference/sdk/shardlens/exporter-otel/interfaces/opentelemetryexporteroptions/) ## Functions [Section titled “Functions”](#functions) * [openTelemetryExporter](/Shardlens/reference/sdk/shardlens/exporter-otel/functions/opentelemetryexporter/) ## References [Section titled “References”](#references) ### DEFAULT_DURATION_BUCKETS [Section titled “DEFAULT_DURATION_BUCKETS”](#default_duration_buckets) Re-exports [DEFAULT_DURATION_BUCKETS](/Shardlens/reference/sdk/shardlens/exporter-prometheus/variables/default_duration_buckets/) # prometheusExporter > **prometheusExporter**(`options?`): [`PrometheusExporter`](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/prometheusexporter/) Defined in: [packages/exporter-prometheus/src/index.ts:88](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L88) Creates the exporter. Pass it to `createShardlens(client, { exporters: [it] })`. ## Parameters [Section titled “Parameters”](#parameters) ### options? [Section titled “options?”](#options) [`PrometheusExporterOptions`](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/prometheusexporteroptions/) = `{}` ## Returns [Section titled “Returns”](#returns) [`PrometheusExporter`](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/prometheusexporter/) # prometheusName > **prometheusName**(`metric`, `prefix?`): `string` Defined in: [packages/exporter-prometheus/src/index.ts:61](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L61) Prometheus metric name for a Shardlens instrument, following Prometheus naming conventions. ## Parameters [Section titled “Parameters”](#parameters) ### metric [Section titled “metric”](#metric) `"interactions"` | `"guilds"` | `"interaction_response"` | `"interaction_handler"` | `"interaction_errors"` | `"rest_requests"` | `"rest_invalid_requests"` | `"ratelimits"` | `"shard_events"` | `"guild_events"` | `"custom_events"` | `"entitlements"` | `"shard_ping"` | `"eventloop_delay_p99"` | `"memory"` | `"cache_size"` | `"identify_remaining"` ### prefix? [Section titled “prefix?”](#prefix) `string` = `DEFAULT_PREFIX` ## Returns [Section titled “Returns”](#returns) `string` # MetricsServer Defined in: [packages/exporter-prometheus/src/server.ts:14](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/server.ts#L14) A running metrics server. ## Properties [Section titled “Properties”](#properties) ### port [Section titled “port”](#port) > `readonly` **port**: `number` Defined in: [packages/exporter-prometheus/src/server.ts:16](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/server.ts#L16) The port it listens on (the one chosen by the system for port `0`), or `0` while it can’t listen yet. ## Methods [Section titled “Methods”](#methods) ### close() [Section titled “close()”](#close) > **close**(): `Promise`<`void`> Defined in: [packages/exporter-prometheus/src/server.ts:18](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/server.ts#L18) Stops listening and closes open connections. #### Returns [Section titled “Returns”](#returns) `Promise`<`void`> # PrometheusExporter Defined in: [packages/exporter-prometheus/src/index.ts:35](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L35) The exporter returned by [prometheusExporter](/Shardlens/reference/sdk/shardlens/exporter-prometheus/functions/prometheusexporter/). ## Extends [Section titled “Extends”](#extends) * [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/) ## Properties [Section titled “Properties”](#properties) ### name [Section titled “name”](#name) > `readonly` **name**: `string` Defined in: packages/core/dist/index.d.ts:27 Short name, used when counting errors (`exporter:`). #### Inherited from [Section titled “Inherited from”](#inherited-from) [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/).[`name`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/#name) *** ### registry [Section titled “registry”](#registry) > `readonly` **registry**: `Registry` Defined in: [packages/exporter-prometheus/src/index.ts:37](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L37) The registry holding the Shardlens metrics. Merge it with yours, or serve it with [PrometheusExporter.serve](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/prometheusexporter/#serve). ## Methods [Section titled “Methods”](#methods) ### observe() [Section titled “observe()”](#observe) > **observe**(`event`): `void` Defined in: packages/core/dist/index.d.ts:28 #### Parameters [Section titled “Parameters”](#parameters) ##### event [Section titled “event”](#event) `WireEvent` #### Returns [Section titled “Returns”](#returns) `void` #### Inherited from [Section titled “Inherited from”](#inherited-from-1) [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/).[`observe`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/#observe) *** ### serve() [Section titled “serve()”](#serve) > **serve**(`options?`): `Promise`<[`MetricsServer`](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/metricsserver/)> Defined in: [packages/exporter-prometheus/src/index.ts:43](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L43) Serves `GET /metrics` on its own small HTTP server. Listens on `127.0.0.1` unless you choose another host: put a firewall or reverse proxy in front before exposing it. Never rejects: if the port is taken, it warns and tries again every 10 seconds. #### Parameters [Section titled “Parameters”](#parameters-1) ##### options? [Section titled “options?”](#options) [`ServeOptions`](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/serveoptions/) #### Returns [Section titled “Returns”](#returns-1) `Promise`<[`MetricsServer`](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/metricsserver/)> *** ### shutdown()? [Section titled “shutdown()?”](#shutdown) > `optional` **shutdown**(): `void` | `Promise`<`void`> Defined in: packages/core/dist/index.d.ts:29 #### Returns [Section titled “Returns”](#returns-2) `void` | `Promise`<`void`> #### Inherited from [Section titled “Inherited from”](#inherited-from-2) [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/).[`shutdown`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/#shutdown) # PrometheusExporterOptions Defined in: [packages/exporter-prometheus/src/index.ts:22](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L22) Options for [prometheusExporter](/Shardlens/reference/sdk/shardlens/exporter-prometheus/functions/prometheusexporter/). Values that can’t be used are replaced by the default, with a warning. ## Properties [Section titled “Properties”](#properties) ### buckets? [Section titled “buckets?”](#buckets) > `optional` **buckets?**: readonly `number`\[] Defined in: [packages/exporter-prometheus/src/index.ts:31](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L31) Bucket boundaries, in seconds and increasing, for the response-time and handler histograms. *** ### prefix? [Section titled “prefix?”](#prefix) > `optional` **prefix?**: `string` Defined in: [packages/exporter-prometheus/src/index.ts:29](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L29) Prefix for every metric name. Default `shardlens_`. *** ### registry? [Section titled “registry?”](#registry) > `optional` **registry?**: `Registry`<`"text/plain; version=0.0.4; charset=utf-8"`> Defined in: [packages/exporter-prometheus/src/index.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/index.ts#L27) Registry to register the metrics on. Default: a new registry, so nothing clashes with your own metrics. One that already holds a metric of the same name is not used. # ServeOptions Defined in: [packages/exporter-prometheus/src/server.ts:6](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/server.ts#L6) Where the metrics server listens. ## Properties [Section titled “Properties”](#properties) ### host? [Section titled “host?”](#host) > `optional` **host?**: `string` Defined in: [packages/exporter-prometheus/src/server.ts:10](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/server.ts#L10) Default `127.0.0.1`. Use `0.0.0.0` when Prometheus runs in another container or on another machine. *** ### port? [Section titled “port?”](#port) > `optional` **port?**: `number` Defined in: [packages/exporter-prometheus/src/server.ts:8](https://github.com/Kkkermit/Shardlens/blob/main/packages/exporter-prometheus/src/server.ts#L8) Default `9464`. Give each process of a sharded bot its own port. # @shardlens/exporter-prometheus `@shardlens/exporter-prometheus`: Shardlens bot-health metrics in Prometheus format, for Grafana. Works with or without a Shardlens collector. Metrics never carry a user or server label. ## Interfaces [Section titled “Interfaces”](#interfaces) * [MetricsServer](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/metricsserver/) * [PrometheusExporter](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/prometheusexporter/) * [PrometheusExporterOptions](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/prometheusexporteroptions/) * [ServeOptions](/Shardlens/reference/sdk/shardlens/exporter-prometheus/interfaces/serveoptions/) ## Variables [Section titled “Variables”](#variables) * [DEFAULT_DURATION_BUCKETS](/Shardlens/reference/sdk/shardlens/exporter-prometheus/variables/default_duration_buckets/) ## Functions [Section titled “Functions”](#functions) * [prometheusExporter](/Shardlens/reference/sdk/shardlens/exporter-prometheus/functions/prometheusexporter/) * [prometheusName](/Shardlens/reference/sdk/shardlens/exporter-prometheus/functions/prometheusname/) # DEFAULT_DURATION_BUCKETS > `const` **DEFAULT_DURATION_BUCKETS**: readonly `number`\[] Defined in: packages/core/dist/index.d.ts:40 Histogram bucket boundaries, in seconds, placed around Discord’s 3-second response deadline. # createShardlensHttp > **createShardlensHttp**(`options`): [`ShardlensHttp`](/Shardlens/reference/sdk/shardlens/http/interfaces/shardlenshttp/) Defined in: [packages/http/src/index.ts:160](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L160) Creates Shardlens for an HTTP-interaction bot. Cheap to call at module scope: nothing runs (no timers, no network) until the first interaction, which suits runtimes such as Cloudflare Workers that forbid I/O at startup. ## Parameters [Section titled “Parameters”](#parameters) ### options [Section titled “options”](#options) [`ShardlensHttpOptions`](/Shardlens/reference/sdk/shardlens/http/interfaces/shardlenshttpoptions/) ## Returns [Section titled “Returns”](#returns) [`ShardlensHttp`](/Shardlens/reference/sdk/shardlens/http/interfaces/shardlenshttp/) # RawInteraction Defined in: [packages/http/src/interaction.ts:15](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L15) The parts of a raw Discord interaction payload Shardlens reads. `APIInteraction` from `discord-api-types` (and the JSON Discord posts to your Interactions Endpoint URL) fits this shape. ## Properties [Section titled “Properties”](#properties) ### authorizing_integration_owners? [Section titled “authorizing_integration_owners?”](#authorizing_integration_owners) > `optional` **authorizing_integration_owners?**: `Partial`<`Record`<`string`, `string`>> Defined in: [packages/http/src/interaction.ts:26](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L26) *** ### channel? [Section titled “channel?”](#channel) > `optional` **channel?**: `object` Defined in: [packages/http/src/interaction.ts:20](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L20) #### type? [Section titled “type?”](#type) > `optional` **type?**: `number` *** ### context? [Section titled “context?”](#context) > `optional` **context?**: `number` Defined in: [packages/http/src/interaction.ts:25](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L25) *** ### data? [Section titled “data?”](#data) > `optional` **data?**: [`RawInteractionData`](/Shardlens/reference/sdk/shardlens/http/interfaces/rawinteractiondata/) Defined in: [packages/http/src/interaction.ts:18](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L18) *** ### entitlements? [Section titled “entitlements?”](#entitlements) > `optional` **entitlements?**: readonly `unknown`\[] Defined in: [packages/http/src/interaction.ts:27](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L27) *** ### guild_id? [Section titled “guild_id?”](#guild_id) > `optional` **guild_id?**: `string` Defined in: [packages/http/src/interaction.ts:19](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L19) *** ### guild_locale? [Section titled “guild_locale?”](#guild_locale) > `optional` **guild_locale?**: `string` Defined in: [packages/http/src/interaction.ts:24](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L24) *** ### id [Section titled “id”](#id) > **id**: `string` Defined in: [packages/http/src/interaction.ts:16](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L16) *** ### locale? [Section titled “locale?”](#locale) > `optional` **locale?**: `string` Defined in: [packages/http/src/interaction.ts:23](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L23) *** ### member? [Section titled “member?”](#member) > `optional` **member?**: `object` Defined in: [packages/http/src/interaction.ts:21](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L21) #### permissions? [Section titled “permissions?”](#permissions) > `optional` **permissions?**: `string` #### user? [Section titled “user?”](#user) > `optional` **user?**: [`RawUser`](/Shardlens/reference/sdk/shardlens/http/interfaces/rawuser/) *** ### message? [Section titled “message?”](#message) > `optional` **message?**: `object` Defined in: [packages/http/src/interaction.ts:28](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L28) #### interaction? [Section titled “interaction?”](#interaction) > `optional` **interaction?**: `object` ##### interaction.name? [Section titled “interaction.name?”](#interactionname) > `optional` **name?**: `string` *** ### type [Section titled “type”](#type-1) > **type**: `number` Defined in: [packages/http/src/interaction.ts:17](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L17) *** ### user? [Section titled “user?”](#user-1) > `optional` **user?**: [`RawUser`](/Shardlens/reference/sdk/shardlens/http/interfaces/rawuser/) Defined in: [packages/http/src/interaction.ts:22](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L22) # RawInteractionData Defined in: [packages/http/src/interaction.ts:32](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L32) The `data` of a raw interaction: the command, its options, or the component or modal’s custom ID. ## Properties [Section titled “Properties”](#properties) ### component_type? [Section titled “component_type?”](#component_type) > `optional` **component_type?**: `number` Defined in: [packages/http/src/interaction.ts:39](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L39) *** ### custom_id? [Section titled “custom_id?”](#custom_id) > `optional` **custom_id?**: `string` Defined in: [packages/http/src/interaction.ts:38](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L38) *** ### guild_id? [Section titled “guild_id?”](#guild_id) > `optional` **guild_id?**: `string` Defined in: [packages/http/src/interaction.ts:36](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L36) *** ### id? [Section titled “id?”](#id) > `optional` **id?**: `string` Defined in: [packages/http/src/interaction.ts:33](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L33) *** ### name? [Section titled “name?”](#name) > `optional` **name?**: `string` Defined in: [packages/http/src/interaction.ts:34](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L34) *** ### options? [Section titled “options?”](#options) > `optional` **options?**: readonly [`RawOption`](/Shardlens/reference/sdk/shardlens/http/interfaces/rawoption/)\[] Defined in: [packages/http/src/interaction.ts:37](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L37) *** ### type? [Section titled “type?”](#type) > `optional` **type?**: `number` Defined in: [packages/http/src/interaction.ts:35](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L35) # RawOption Defined in: [packages/http/src/interaction.ts:43](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L43) A command option as Discord sends it; subcommands and groups hold their own `options`. ## Properties [Section titled “Properties”](#properties) ### focused? [Section titled “focused?”](#focused) > `optional` **focused?**: `boolean` Defined in: [packages/http/src/interaction.ts:47](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L47) *** ### name [Section titled “name”](#name) > **name**: `string` Defined in: [packages/http/src/interaction.ts:44](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L44) *** ### options? [Section titled “options?”](#options) > `optional` **options?**: readonly `RawOption`\[] Defined in: [packages/http/src/interaction.ts:48](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L48) *** ### type [Section titled “type”](#type) > **type**: `number` Defined in: [packages/http/src/interaction.ts:45](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L45) *** ### value? [Section titled “value?”](#value) > `optional` **value?**: `unknown` Defined in: [packages/http/src/interaction.ts:46](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L46) # RawUser Defined in: [packages/http/src/interaction.ts:52](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L52) The user who ran an interaction. Only the ID is read, plus username and avatar in audit mode. ## Properties [Section titled “Properties”](#properties) ### avatar? [Section titled “avatar?”](#avatar) > `optional` **avatar?**: `string` | `null` Defined in: [packages/http/src/interaction.ts:55](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L55) *** ### id [Section titled “id”](#id) > **id**: `string` Defined in: [packages/http/src/interaction.ts:53](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L53) *** ### username? [Section titled “username?”](#username) > `optional` **username?**: `string` Defined in: [packages/http/src/interaction.ts:54](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/interaction.ts#L54) # ShardlensHttp Defined in: [packages/http/src/index.ts:90](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L90) ## Methods [Section titled “Methods”](#methods) ### flush() [Section titled “flush()”](#flush) > **flush**(): `Promise`<`void`> Defined in: [packages/http/src/index.ts:123](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L123) Waits for hashing to finish, then sends queued events. A wrapped handler given a `waitUntil` does this itself; use it on a platform without one, before you return. #### Returns [Section titled “Returns”](#returns) `Promise`<`void`> *** ### forgetUser() [Section titled “forgetUser()”](#forgetuser) > **forgetUser**(`userId`): `Promise`<{ `erased`: `number`; } | `undefined`> Defined in: [packages/http/src/index.ts:118](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L118) Deletes everything the collector stored about a user. Never throws. #### Parameters [Section titled “Parameters”](#parameters) ##### userId [Section titled “userId”](#userid) `string` #### Returns [Section titled “Returns”](#returns-1) `Promise`<{ `erased`: `number`; } | `undefined`> *** ### isOptedOut() [Section titled “isOptedOut()”](#isoptedout) > **isOptedOut**(`userId`): `boolean` Defined in: [packages/http/src/index.ts:116](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L116) #### Parameters [Section titled “Parameters”](#parameters-1) ##### userId [Section titled “userId”](#userid-1) `string` #### Returns [Section titled “Returns”](#returns-2) `boolean` *** ### on() [Section titled “on()”](#on) > **on**(`event`, `listener`): () => `void` Defined in: [packages/http/src/index.ts:129](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L129) Listens for the SDK’s internal errors (tokens and request bodies removed). Returns a function that unsubscribes. #### Parameters [Section titled “Parameters”](#parameters-2) ##### event [Section titled “event”](#event) `"error"` ##### listener [Section titled “listener”](#listener) (`name`, `error`) => `void` #### Returns [Section titled “Returns”](#returns-3) () => `void` *** ### optIn() [Section titled “optIn()”](#optin) > **optIn**(`userId`): `void` Defined in: [packages/http/src/index.ts:115](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L115) Records this user’s events again. #### Parameters [Section titled “Parameters”](#parameters-3) ##### userId [Section titled “userId”](#userid-2) `string` #### Returns [Section titled “Returns”](#returns-4) `void` *** ### optOut() [Section titled “optOut()”](#optout) > **optOut**(`userId`): `void` Defined in: [packages/http/src/index.ts:113](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L113) Drops this user’s events from now on (for example after `/privacy opt-out`). Persist the choice yourself. #### Parameters [Section titled “Parameters”](#parameters-4) ##### userId [Section titled “userId”](#userid-3) `string` #### Returns [Section titled “Returns”](#returns-5) `void` *** ### shutdown() [Section titled “shutdown()”](#shutdown) > **shutdown**(`options?`): `Promise`<`void`> Defined in: [packages/http/src/index.ts:125](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L125) Sends what is queued and stops. Call it when a long-running server stops; Workers don’t need it. #### Parameters [Section titled “Parameters”](#parameters-5) ##### options? [Section titled “options?”](#options) ###### timeoutMs? [Section titled “timeoutMs?”](#timeoutms) `number` #### Returns [Section titled “Returns”](#returns-6) `Promise`<`void`> *** ### stats() [Section titled “stats()”](#stats) > **stats**(): `ClientStats` Defined in: [packages/http/src/index.ts:127](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L127) The SDK’s own health: queue depth, drops and internal errors. #### Returns [Section titled “Returns”](#returns-7) `ClientStats` *** ### track() [Section titled “track()”](#track) > **track**<`N`>(`name`, `props?`, `context?`, `waitUntil?`): `void` Defined in: [packages/http/src/index.ts:106](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L106) Records a custom event. Invalid events are dropped and counted, never thrown. On serverless runtimes pass the request’s `ctx` as `waitUntil`, or the event waits for the next interaction. #### Type Parameters [Section titled “Type Parameters”](#type-parameters) ##### N [Section titled “N”](#n) `N` *extends* `string` #### Parameters [Section titled “Parameters”](#parameters-6) ##### name [Section titled “name”](#name) `N` ##### props? [Section titled “props?”](#props) `CustomEventProps`<`N`> ##### context? [Section titled “context?”](#context) [`TrackContext`](/Shardlens/reference/sdk/shardlens/http/interfaces/trackcontext/) ##### waitUntil? [Section titled “waitUntil?”](#waituntil) [`WaitUntilContext`](/Shardlens/reference/sdk/shardlens/http/interfaces/waituntilcontext/) #### Returns [Section titled “Returns”](#returns-8) `void` *** ### wrapInteractionHandler() [Section titled “wrapInteractionHandler()”](#wrapinteractionhandler) > **wrapInteractionHandler**<`I`, `A`, `R`>(`handler`): (`interaction`, …`args`) => `Promise`<`Awaited`<`R`>> Defined in: [packages/http/src/index.ts:99](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L99) Wraps the function that answers an interaction. The wrapped function records the interaction, how long your response took against Discord’s 3-second deadline, and any error (re-thrown unchanged). Return the interaction response body (or a `Response`) from your handler as usual. If any argument has a `waitUntil` method (a Workers `ExecutionContext`, for example), events are sent through it after your response, so the runtime doesn’t stop before they leave. PING interactions are not recorded. #### Type Parameters [Section titled “Type Parameters”](#type-parameters-1) ##### I [Section titled “I”](#i) `I` *extends* [`RawInteraction`](/Shardlens/reference/sdk/shardlens/http/interfaces/rawinteraction/) ##### A [Section titled “A”](#a) `A` *extends* `unknown`\[] ##### R [Section titled “R”](#r) `R` #### Parameters [Section titled “Parameters”](#parameters-7) ##### handler [Section titled “handler”](#handler) (`interaction`, …`args`) => `R` | `Promise`<`R`> #### Returns [Section titled “Returns”](#returns-9) (`interaction`, …`args`) => `Promise`<`Awaited`<`R`>> # ShardlensHttpOptions Defined in: [packages/http/src/index.ts:45](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L45) ## Properties [Section titled “Properties”](#properties) ### apiKey? [Section titled “apiKey?”](#apikey) > `optional` **apiKey?**: `string` Defined in: [packages/http/src/index.ts:49](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L49) Ingest-only API key (`slk_ingest_…`). On Workers, keep it in a secret (`wrangler secret put`). *** ### auditIncludeProfile? [Section titled “auditIncludeProfile?”](#auditincludeprofile) > `optional` **auditIncludeProfile?**: `boolean` Defined in: [packages/http/src/index.ts:53](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L53) Audit mode only: send each user’s username and avatar with their ID. Default `true`; `false` records IDs only. *** ### captureOptionValues? [Section titled “captureOptionValues?”](#captureoptionvalues) > `optional` **captureOptionValues?**: readonly `string`\[] Defined in: [packages/http/src/index.ts:61](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L61) Option names whose values may be recorded. 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, secrets redacted. Default none. *** ### dryRun? [Section titled “dryRun?”](#dryrun) > `optional` **dryRun?**: `boolean` Defined in: [packages/http/src/index.ts:77](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L77) Print events instead of sending them. *** ### endpoint? [Section titled “endpoint?”](#endpoint) > `optional` **endpoint?**: `string` Defined in: [packages/http/src/index.ts:47](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L47) Your collector’s URL. HTTPS, or HTTP to localhost only. Leave out with `apiKey` to use exporters only. *** ### environment? [Section titled “environment?”](#environment) > `optional` **environment?**: `string` Defined in: [packages/http/src/index.ts:65](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L65) Separates staging from production. Default `'production'`. *** ### exporters? [Section titled “exporters?”](#exporters) > `optional` **exporters?**: readonly [`ShardlensExporter`](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/shardlensexporter/)\[] Defined in: [packages/http/src/index.ts:75](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L75) In-process metrics exporters. They get every event, never with a user. *** ### fetch? [Section titled “fetch?”](#fetch) > `optional` **fetch?**: {(`input`, `init?`): `Promise`<`Response`>; (`input`, `init?`): `Promise`<`Response`>; } Defined in: [packages/http/src/index.ts:81](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L81) Override `fetch` (tests, proxies). #### Call Signature [Section titled “Call Signature”](#call-signature) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters) ###### input [Section titled “input”](#input) `URL` | `RequestInfo` ###### init? [Section titled “init?”](#init) `RequestInit` ##### Returns [Section titled “Returns”](#returns) `Promise`<`Response`> #### Call Signature [Section titled “Call Signature”](#call-signature-1) > (`input`, `init?`): `Promise`<`Response`> [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ##### Parameters [Section titled “Parameters”](#parameters-1) ###### input [Section titled “input”](#input-1) `string` | `URL` | `Request` ###### init? [Section titled “init?”](#init-1) `RequestInit` ##### Returns [Section titled “Returns”](#returns-1) `Promise`<`Response`> *** ### instance? [Section titled “instance?”](#instance) > `optional` **instance?**: `string` Defined in: [packages/http/src/index.ts:69](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L69) A label for this deployment in SDK health, for example the Worker name. Default `'http'`. *** ### logger? [Section titled “logger?”](#logger) > `optional` **logger?**: `Logger` Defined in: [packages/http/src/index.ts:79](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L79) Where SDK warnings go. Default `console`. *** ### mode? [Section titled “mode?”](#mode) > `optional` **mode?**: `"privacy"` | `"audit"` Defined in: [packages/http/src/index.ts:51](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L51) `'privacy'` (default) or `'audit'`; audit only takes effect when the collector is in audit mode too. *** ### normaliseCustomId? [Section titled “normaliseCustomId?”](#normalisecustomid) > `optional` **normaliseCustomId?**: (`customId`) => `string` Defined in: [packages/http/src/index.ts:63](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L63) Replaces the default custom-ID normaliser (numbers and IDs become `*`). #### Parameters [Section titled “Parameters”](#parameters-2) ##### customId [Section titled “customId”](#customid) `string` #### Returns [Section titled “Returns”](#returns-2) `string` *** ### optedOut? [Section titled “optedOut?”](#optedout) > `optional` **optedOut?**: `Iterable`<`string` | `bigint`, `any`, `any`> Defined in: [packages/http/src/index.ts:71](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L71) Users who opted out earlier. Their events are dropped in-process. BigInt IDs from a database are accepted. *** ### release? [Section titled “release?”](#release) > `optional` **release?**: `string` Defined in: [packages/http/src/index.ts:67](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L67) Your bot’s version, to compare releases. *** ### saltPeriod? [Section titled “saltPeriod?”](#saltperiod) > `optional` **saltPeriod?**: `SaltPeriod` Defined in: [packages/http/src/index.ts:55](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L55) Informational; the collector decides. Default `'month'`. *** ### sampleRate? [Section titled “sampleRate?”](#samplerate) > `optional` **sampleRate?**: `Readonly`<`Record`<`string`, `number`>> Defined in: [packages/http/src/index.ts:73](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L73) Sample rate per event type in (0, 1]. # TrackContext Defined in: [packages/http/src/index.ts:85](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L85) Who a custom event is about. The user ID is hashed before it is sent. ## Properties [Section titled “Properties”](#properties) ### guildId? [Section titled “guildId?”](#guildid) > `optional` **guildId?**: `string` | `null` Defined in: [packages/http/src/index.ts:87](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L87) *** ### userId? [Section titled “userId?”](#userid) > `optional` **userId?**: `string` Defined in: [packages/http/src/index.ts:86](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/index.ts#L86) # WaitUntilContext Defined in: [packages/http/src/transport.ts:4](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/transport.ts#L4) Anything with `waitUntil`, such as a Cloudflare Workers `ExecutionContext`. ## Methods [Section titled “Methods”](#methods) ### waitUntil() [Section titled “waitUntil()”](#waituntil) > **waitUntil**(`promise`): `void` Defined in: [packages/http/src/transport.ts:6](https://github.com/Kkkermit/Shardlens/blob/main/packages/http/src/transport.ts#L6) Keeps the runtime running until `promise` settles, after the response has been sent. #### Parameters [Section titled “Parameters”](#parameters) ##### promise [Section titled “promise”](#promise) `Promise`<`unknown`> #### Returns [Section titled “Returns”](#returns) `void` # @shardlens/http `@shardlens/http`: Shardlens for Discord bots that receive interactions over HTTP (an Interactions Endpoint URL) instead of the gateway: Cloudflare Workers, Deno, Bun, or Node with `@discordjs/core`. Web-standard APIs only. ## Interfaces [Section titled “Interfaces”](#interfaces) * [RawInteraction](/Shardlens/reference/sdk/shardlens/http/interfaces/rawinteraction/) * [RawInteractionData](/Shardlens/reference/sdk/shardlens/http/interfaces/rawinteractiondata/) * [RawOption](/Shardlens/reference/sdk/shardlens/http/interfaces/rawoption/) * [RawUser](/Shardlens/reference/sdk/shardlens/http/interfaces/rawuser/) * [ShardlensHttp](/Shardlens/reference/sdk/shardlens/http/interfaces/shardlenshttp/) * [ShardlensHttpOptions](/Shardlens/reference/sdk/shardlens/http/interfaces/shardlenshttpoptions/) * [TrackContext](/Shardlens/reference/sdk/shardlens/http/interfaces/trackcontext/) * [WaitUntilContext](/Shardlens/reference/sdk/shardlens/http/interfaces/waituntilcontext/) ## Functions [Section titled “Functions”](#functions) * [createShardlensHttp](/Shardlens/reference/sdk/shardlens/http/functions/createshardlenshttp/) ## References [Section titled “References”](#references) ### CustomEvents [Section titled “CustomEvents”](#customevents) Re-exports [CustomEvents](/Shardlens/reference/sdk/shardlens/discordjs/interfaces/customevents/) # Decision records > Architecture decision records — why Shardlens is built the way it is. Significant decisions are recorded as short architecture decision records (ADRs) in [`docs/adr`](https://github.com/Kkkermit/Shardlens/tree/main/docs/adr). Each one states the context, the decision and its consequences. A new decision that changes an old one gets a new record, and the old one is marked as superseded. | ADR | Decision | | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | | [0001](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0001-salted-user-hashing.md) | Pseudonymise user IDs in-process with rotating, destroyed salts | | [0002](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0002-audit-mode.md) | Audit mode is a two-sided, encrypted, time-limited opt-in | | [0003](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0003-storage.md) | PostgreSQL by default, partitioned, no extensions | | [0004](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0004-schema-versioning.md) | Wire-format versioning: additive within a major | | [0005](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0005-typescript-6-pin.md) | Pin TypeScript to 6.0.x | | [0006](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0006-intents-reverification.md) | Gateway intents re-verified against Discord’s docs | | [0007](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0007-m0-reference-code-changes.md) | Changes to the spec’s reference code during M0 | | [0008](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0008-release-gating.md) | npm releases stay switched off until trusted publishing is proven | | [0009](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0009-rest-response-safety.md) | Never read or cancel shared REST response bodies | | [0010](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0010-m1-collector-decisions.md) | Collector and dashboard choices made during M1 | | [0011](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0011-m2-privacy-admin-decisions.md) | Privacy, audit and admin choices made during M2 | | [0012](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0012-embedded-mode-on-pglite.md) | Run embedded mode on PGlite, not SQLite | | [0013](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0013-m3-m4-decisions.md) | Choices made during M3 and M4 | | [0014](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0014-quality-and-hardening-pass.md) | Pre-release quality and hardening pass | | [0015](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0015-reports-and-identified-users.md) | Reports in Discord, and what identified mode may collect | | [0016](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0016-corrections-from-simulated-installs.md) | Corrections from simulated installs | | [0017](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0017-version-1.md) | Version 1.0 and what it promises | | [0018](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0018-message-commands.md) | Record message (prefix) commands the bot reports | | [0019](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0019-event-sinks.md) | Copy events into the owner’s own database through sinks | To propose a decision, copy [`0000-template.md`](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0000-template.md) to the next number and open a pull request. # Development > Setting up the monorepo and running everything locally. ## Requirements [Section titled “Requirements”](#requirements) Node 24.11 or later, pnpm 12 (`corepack enable`) and Docker. ## Set up [Section titled “Set up”](#set-up) 1. Install dependencies and run every check once: ```sh pnpm install pnpm check # format check, lint, typecheck, tests, builds, package lint, API reports, unused code, size limits ``` 2. Start PostgreSQL for development (on `127.0.0.1:5432`): ```sh docker compose -f deploy/docker-compose.dev.yml up -d ``` 3. Create `apps/collector/.env` from `deploy/.env.example`, with `DATABASE_URL=postgres://shardlens:shardlens-dev@127.0.0.1:5432/shardlens` and `SHARDLENS_PUBLIC_URL=http://localhost:8080`. 4. Build, start the collector and load 30 days of fictional demo data: ```sh pnpm build node --env-file=apps/collector/.env apps/collector/dist/main.js node --env-file=apps/collector/.env apps/collector/dist/cli/seed.js ``` Open `http://localhost:8080` and sign in with the read key from your `.env`. ## Layout [Section titled “Layout”](#layout) * packages/ * schema/ wire format (zod), JSON Schema, metric and data-collected registers * … * core/ zero-dependency SDK core * … * discordjs/ discord.js adapter, with the overhead benchmark in bench/ * … * http/ adapter for HTTP-interaction bots * … * client/ typed reader of a collector, for your own dashboard or scripts * … * exporter-prometheus/ and exporter-otel/ metrics exporters * … * cli/ the shardlens CLI * … * apps/ * collector/ Fastify and PostgreSQL * … * dashboard/ React dashboard served by the collector * … * docs/ this site * … * examples/ basic-bot, sharded-bot, hybrid-sharding, audit-mode, cloudflare-worker * … * deploy/ Docker Compose, Caddyfile, .env.example * … * docs/adr/ architecture decision records * … ## Rules [Section titled “Rules”](#rules) The rules every change follows are in [`AGENTS.md`](https://github.com/Kkkermit/Shardlens/blob/main/AGENTS.md), for people and coding agents alike. The most important: 1. The SDK never throws into, blocks or crashes the host bot. 2. Never store or log tokens, REST paths, request headers, message content or raw user IDs. 3. Privacy mode is the default. No per-user views. 4. Public discord.js APIs only. 5. Changes to collected fields, metrics, options or the HTTP API update these docs in the same pull request. ## Docs [Section titled “Docs”](#docs) ```sh pnpm --filter @shardlens/docs dev ``` Code samples live in `apps/docs/snippets/` and are type-checked, so they can’t drift from the API. The data-collected, metrics, SDK options, SDK reference and HTTP API pages are generated from the code. ## The public demo [Section titled “The public demo”](#the-public-demo) The public demo is an ordinary collector with fictional data and `SHARDLENS_DEMO=true`, which lets anyone view the dashboard read-only (settings, keys, alerts, audit data and ingest stay locked): ```sh echo "SHARDLENS_DEMO=true" >> .env # next to docker-compose.yml docker compose up -d docker compose exec collector node dist/cli/seed.js ``` The seeder sends 30 days of made-up traffic through the real SDK client, so salts, hashing and rollups are exercised exactly as for a real bot. It refuses to run against a database that already has interactions, so it can’t mix fictional numbers into a real bot’s analytics. # Releasing > Changesets, versioning, npm provenance and container images. ## Changesets [Section titled “Changesets”](#changesets) Every change to a published package needs a changeset describing it for the changelog: ```sh pnpm changeset ``` Pick the packages, the kind of bump (patch, minor or major) and write one or two sentences for users. Commit messages follow [Conventional Commits](https://www.conventionalcommits.org). ## How a release happens [Section titled “How a release happens”](#how-a-release-happens) 1. Merged changesets collect in a **Version Packages** pull request opened by the release workflow. 2. Merging that pull request publishes the packages to npm with [provenance](https://docs.npmjs.com/generating-provenance-statements), using npm trusted publishing (no npm token is stored in the repository). 3. The collector image is built, signed and pushed to the GitHub Container Registry with full, minor and major version tags. ## What a version number promises [Section titled “What a version number promises”](#what-a-version-number-promises) Within a major version, nothing covered by semantic versioning breaks: the packages’ exported APIs (recorded in each package’s `etc/*.api.md` report), the CLI, the collector’s HTTP API and environment variables, and data in an existing database. A breaking change needs a `major` changeset and a migration note. The wire format has its own major version, and a collector accepts the current and the previous one. The full list is in [ADR 0017](https://github.com/Kkkermit/Shardlens/blob/main/docs/adr/0017-version-1.md). # Testing > The test layers and how to run each one. Every change comes with tests, and every bug fix with a regression test. | Layer | Command | What it proves | | ------------------ | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Unit | `pnpm test` | Hashing, normaliser, redaction, histograms, queue, schema rules | | Property-based | (part of `pnpm test`, with fast-check) | The queue never exceeds capacity; redaction catches token shapes | | Adapter | `pnpm --filter @shardlens/discordjs test` | Real discord.js `Client` with raw payloads: each event is recorded, nothing throws | | Chaos | (part of the adapter tests) | Collector down, slow, `500`, `429` or killed mid-flush: the bot still answers, memory stays capped, no duplicates | | Integration | `pnpm --filter @shardlens/collector test:int` | Real PostgreSQL 16 and 17 (Testcontainers): ingest, rollups, salts, retention, auth on every route | | End to end | `pnpm --filter @shardlens/dashboard test:e2e` | A real collector with seeded data: every dashboard page with axe (WCAG 2.1 AA and best practices, light and dark), XSS-safe rendering, CSP, sign-in and sign-out, ended sessions, error states, unknown commands, keyboard focus, browser locale, server list state, failing commands on a server’s page, admin gating, audit mode and its links to failed runs | | Benchmark | `pnpm --filter @shardlens/discordjs bench` | SDK CPU and memory overhead against the targets | | Simulated installs | `pnpm sim` | The packed packages, installed with npm into four bots that coding agents set up (one of them sharded) and run against a fake Discord: exact counts, no leaked IDs, names, tokens or typed text, clean shutdown (weekly, see `tests/sim/README.md`) | | Docs | `pnpm --filter @shardlens/docs build` | Code samples compile; no broken links | Integration, end-to-end and simulated-install tests need Docker. Before the first end-to-end run, install the browser with `pnpm --filter @shardlens/dashboard exec playwright install chromium`. ## One package at a time [Section titled “One package at a time”](#one-package-at-a-time) ```sh pnpm --filter @shardlens/core test pnpm --filter @shardlens/core test -- --watch ``` ## Public API changes [Section titled “Public API changes”](#public-api-changes) The public API of each published package is tracked in an API report. After changing it on purpose: ```sh pnpm api ``` and commit the updated report with your change.