-
-
Notifications
You must be signed in to change notification settings - Fork 40
@Guard
You can use functions that are executed before your event to determine if it's executed. For example, if you want to apply a prefix to the messages, you can simply use the @Guard
decorator.
The order of execution of the guards is done according to their position in the list, so they will be executed in order (from top to bottom).
Guards works also with @Command
and @CommandNotFound
.
import {
Discord,
On,
Client,
Guard
} from "@typeit/discord";
import { NotBot } from "./NotBot";
import { Prefix } from "./Prefix";
@Discord()
abstract class AppDiscord {
@On("message")
@Guard(
NotBot, // You can use multiple guard functions, they are excuted in the same order!
Prefix("!")
)
async onMessage([message]: ArgsOf<"message">) {
switch (message.content.toLowerCase()) {
case "hello":
message.reply("Hello!");
break;
default:
message.reply("Command not found");
break;
}
}
}
Notice that the guard function is impacted by your payloadInjection policy
Here is a simple example of a guard function (the payload and the client instance are injected like for events)
Guards work like Koa
's, it's a function passed in parameter (after the Client
's instance) and you will have to call if the guard is passed.
If next isn't called the next guard (or the main method) will not be executed
import { GuardFunction } from "@typeit/discord";
export const NotBot: GuardFunction<"message"> = (
[message],
client,
next
) => {
if (client.user.id !== message.author.id) {
await next();
}
}
If you have to indicate parameters for a guard function you can simple use the "function that returns a function" pattern like this:
import { GuardFunction } from "@typeit/discord";
export function Prefix(text: string, replace: boolean = true) {
const guard: GuardFunction<"message"> = (
[message],
client,
next
) => {
const startWith = message.content.startsWith(text);
if (replace) {
message.content = message.content.replace(text, "");
}
if (startWith) {
await next();
}
};
return guard;
}
As 4th parameter you receive a basic empty object that can be used to transmit data between guard and with your main method.
import { GuardFunction } from "@typeit/discord";
export const NotBot: GuardFunction<"message"> = (
[message],
client,
next,
guardDatas
) => {
if (client.user.id !== message.author.id) {
guardDatas.message = "the NotBot guard passed"
await next();
}
}
import {
Discord,
Command,
Client,
Guard
} from "@typeit/discord";
import { NotBot } from "./NotBot";
import { Prefix } from "./Prefix";
@Discord()
abstract class AppDiscord {
@Command()
@Guard(
NotBot,
Prefix("!")
)
async hello(
command: CommandMessage,
client: Client,
guardDatas: any
) {
console.log(guardDatas.message);
// > the NotBot guard passed
}
}