Command handlers and frameworks
Every bot is laid out differently, but Shardlens only ever needs four things, wherever they live in yours:
- One
createShardlens(client, …)per process, after the client is created and beforeclient.login(). That alone records every slash command, context menu, button, select menu, modal and autocomplete. - Handler time and failures (optional): run your command code through
lens.wrap(), or tell Shardlens when your framework starts and finishes a handler. - Prefix commands, if you have them: one
trackMessageCommandcall where a message is matched to a command. 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”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:
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.lensconst { 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.lensimport { 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”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:
// 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<string, { execute(interaction: ChatInputCommandInteraction): Promise<void> }>; }}
// index.tsconst 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.tsconst 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 runs commands itself and emits an event at each step, so there is nothing to wrap. Listen to those events:
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 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:
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”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) orlens.wrapMessageCommand()(prefix commands), and call the wrapped function exactly as the original was called: inside the sametry, awaited only if it was awaited. If the framework has middleware that runs around every command (CommandKit middleware, Necord interceptors), wrap itsnext()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 withtrackMessageCommandwhere you still have theMessage. - 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”- Top-level
await, or amain()function: either works. CallcreateShardlensbeforeclient.login(). - A
Clientsubclass: call it in the constructor, or right afternew MyClient(). - Embedded mode with no top-level
await(CommonJS, or amain()function): start the collector and createlensin that function, beforeclient.login(). Listeners registered earlier can’t see a locallens: keep it on the client and useclient.lensinside them. - TypeScript compiled to CommonJS (tsc, tsup, esbuild):
require('@shardlens/discordjs')works, and so doesrequire('@shardlens/collector/embedded')on Node 24. ShardingManager, internal sharding, discord-hybrid-sharding: see Sharding. The rule is the same: once in the process that owns theClient.- Settings: read
SHARDLENS_URLandSHARDLENS_INGEST_KEYhowever 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.