Session
A Session is the simplest, most generic object for the sessions API. It replies to interactions it receives and ends after a given TTL.
Further session types are based on this one, and are specifically built for other common use cases.
Usage
Creation
Extend the AbstractSession class:
import { } from '@nyx-discord/plugin-sessions/djs';
There's an optional type argument which is the return type of your session, which will be explained later.
Implementation
Implement the onStart and onEnd methods:
import { } from '@nyx-discord/plugin-sessions/djs';
class extends {
public async () {
// Reply to the startInteraction
}
public async () {
// Do something when the session ends
}
}Your onStart method should perform the initial reply, and onEnd any necessary cleanup logic.
If the onStart method errors, the session will not be registered and the onEnd method will not be called.
Optionally implement handleButton, handleSelectMenu, and handleModal methods to listen to interactions:
import { } from '@nyx-discord/plugin-sessions/djs';
import type { , , } from 'discord.js';
class extends {
protected async (: ) {
// Reply to buttons
return true;
}
protected async (: ) {
// Reply to select menus
return true;
}
protected async (: ) {
// Reply to modals
return true;
}
}Initialization
Somewhere in your code where you want to start a session, create an id for it, instantiate and start the session:
In production your ID should be randomly generated using something like nanoid, and it should be short enough to not collide with extra customId data.
You can use nanoid's collission calculator to find out how short your ID needs to be. Consider a collision only happens if two currently active sessions have the same ID.
const = 'mySessionId';
const = new ({ , : , : });
await .();Component customIds
Given sessions aren't limited to a single Message, and the framework needs to know to which session a given component belongs to, you'll need to go through the buildCustomId method in order to get your customIds.
This will append the necessary information to the customId to allow the framework to know how to route the interaction.
You can also append extra data to it by passing it to the method, and it will be saved in the TypedFields.CustomIdExtra field.
import { } from '@nyx-discord/plugin-sessions/djs';
import { , type } from '@nyx-discord/djs';
import { , , type } from 'discord.js';
public async () {
const = this.('my-data');
const = new ().();
const = new <>().();
await this..({ : [] });
}
protected async (: , : ) {
// We can force the get here (`true`) since we know we passed 'my-data'
const = ..(, true);
await .(); // Replies 'my-data';
return true;
}
}Complex data
If you need to store a complex object as extra data you can consider using the @sapphire/string-store package, which is what
the framework and plugin already uses for serialization to short strings:
import { } from '@nyx-discord/plugin-sessions/djs';
import { , type } from '@nyx-discord/djs';
import { , } from '@sapphire/string-store';
import { , , type } from 'discord.js';
protected static readonly = new ()
// Add an schema with a 'name' field stored as a string and an 'age' field stored as a int32:
.(new (0).('name').('age'));
public async () {
const = ..(0, { : 25, : 'amgelo563' });
const = this.();
const = new ().();
const = new <>().();
await this..({ : [] });
}
protected async (: , : ) {
// We can force the get here (`true`) since we know we passed an extra
const = ..(, true);
const = ..().; // { age: 25, name: 'amgelo563' }
await .(`Name: ${.}, Age: ${.}`);
return true;
}
}Check their documentation for more information and examples.
Session lifecycle
After it's started, a session will have a given TTL before ending. The default is 3 minutes, and it can be overriden per session (in milliseconds):
import { } from '@nyx-discord/plugin-sessions/djs';
class extends {
protected readonly = 10_000; // 10 seconds
}When the session receives an interaction, it can decide whether or not to renew its TTL by returning true on the appropiate handler (or false to not renew it):
import { } from '@nyx-discord/plugin-sessions/djs';
import type { } from 'discord.js';
class extends {
protected async (: ) {
if (.. !== this...) {
await .('You cannot use this button!');
return false;
}
await .('Hello!');
return true;
}
}This is useful to "filter out" interactions that you don't want to renew the TTL of, like from other users or with invalid input.
End promise
Sessions are asynchronous by nature, and you may want to wait for a session to finish before continuing. The getEndPromise() method returns a promise that resolves when the session ends, either by timeout or manual end.
This promise resolves to an SessionEndData object containing the session's final state and result:
const = new ({ , : 'mySessionId', : });
await .();
// Wait for the session to end
const = await .();
.('Session ended');This is particularly useful when you want to perform additional actions after a session completes, such as logging, notifications, or cleanup operations.
Result
Sessions can specify a result that will be passed to awaiters of the session's promise, and the session end event:
import { } from '@nyx-discord/plugin-sessions/djs';
import { , , type } from 'discord.js';
class extends <number> {
protected override = 0;
public async () {}
public async () {}
public async () {
const = this.();
const = new ()
.('Click to increment!')
.();
const = new <>().();
await this..({
: this..(),
: [],
});
}
protected async (: ) {
this. += 1;
await .({ : this..() });
return true;
}
}The default value of the result is null, which is what consumers will receive if you don't set it.
The onEnd() method will be called before the framework gets the result from the session, so you can use it to make some final changes to it,
before it's communicated to the consumer.
Then you can await the session's promise to get the result:
const = new ({ , , : });
await .();
const endData = await .();const result = .;A useful use case is to make sessions where a user is "building" something, and you want to get the final result the user inputted.
Metadata
When extending with plugins, you may want to specify extra data for them to read. You can do so with the Metadata object, saved on the session.
While sessions internally save a Metadata, the return type of #getMeta() is a ReadonlyMetadata,
meaning that external objects can read the object, but not modify it.
const = new ({ , , : });
const = .();
const = ['someKey']; // 'someValue'For a more type-safe approach, you can use TypedFields. Check the Metadata page for more information.
