-
Notifications
You must be signed in to change notification settings - Fork 0
5) Miscellaneous Information
It's common that you want to access your client
in commands, events, or other scenarios where it may not be directly accessible. For this reason, Iubus provides a container
object that also has a client
field with your Client. This way, you can access your client from practically anywhere in your application. To make use of this, simply import container
from Iubus:
// In some arbitrary command file
import { ChatInputCommand, container } from "iubus";
export default new ChatInputCommand({
/* command data... */
run(interaction) {
interaction.reply(`My uptime is ${container.client.uptime}ms!`);
},
});
IMPORTANT NOTE: container
is no black magic - it is literally just an empty object that gets mutated upon calling IubusClient#login
. Thus, this will NOT be populated when your client is not ready/logged in! If you're using it inside commands, events, or inhibitors, it should pretty much always be safe. In general, if you can be certain your client is ready, you should be able to use container
in all kinds of different environments without much problem. However, if you're accessing it inside a scenario separate from your main bot process (like a command deployment script) or in situations where your client is not logged in, container
will just be an empty object.
The whole concept of doing Dependency Injection this way using a "container" is heavily inspired by Sapphire, another discord.js framework, that does this in pretty much the exact same way.
By default, container
only contains a field client
with a reference to your IubusClient
, but you can attach your own properties as well. To do this, just import container
and add a new property like you would with any other object (you should do this in your entry file, otherwise that will just lead to very hard times debugging). Now, any time you import container
, your custom properties will also be present. If you're using TypeScript, you'll also have to augment the iubus module and extend the Container
interface.
import { container, IubusClient } from "iubus";
const client = new IubusClient({
/* some client options ...*/
});
container.db = await getSomeArbitraryDatabaseConnection();
client.login("MY_AWESOME_TOKEN");
declare module "iubus" {
interface Container {
db: SomeArbitraryDatabaseConnection;
}
}