Skip to main content

Accessing the Client

Often when writing your listeners, commands, preconditions, arguments and other pieces you will want to access your instance of SapphireClient. This can be done by accessing the client property on the container interface. The container is a way that Sapphire achieved dependency injection. There are several ways to access the container:

Using this.container inside pieces

When writing code within the closure of a class that extends Piece such as a Command, Listener, Precondition, or Argument you can access the container through this.container. This is by far the easiest way to then access the client, as you can simply write this.container.client. A quick and dirty example of this is:

const { Listener } = require('@sapphire/framework');

class UserEvent extends Listener {
run() {
this.container.logger.info('A user event was received');
}
}
module.exports = {
UserEvent
};

Importing container from Sapphire

When writing code outside of the closure of a class that extends Piece you can import the container from either @sapphire/framework or @sapphire/pieces. A quick and dirty example of this is:

const { container } = require('@sapphire/framework');

function myVeryCoolFunction() {
container.logger.info('myVeryCoolFunction was called');
}
module.exports = {
myVeryCoolFunction
};
info

@sapphire/framework re-exports the container from @sapphire/pieces so from which you import does not matter, they are identical.