The InteractionHandler is responsible for receiving interactions, making it an important part of the system's core.
Usage:
import { ApplicationCommandType } from "discord.js";
import { CreateRow, CreateButton, InteractionHandler} from "ease-discord-js";
export default {
name: "test",
description: "command to test the library",
type: ApplicationCommandType.ChatInput,
run: async(client, interaction) => {
return interaction.reply({content: "Hello World!", components: [
new CreateRow([
new CreateButton({label: "Primary", style: "Primary", customId: "on_click_button"}),
])
]});
}
}
new InteractionHandler({
customId: "on_click_button",
run: async(interaction) => {
return interaction.reply({content: "Primary Button Clicked!", ephemeral: true});
}
})
In the code above, we create a button and define the InteractionHandler with the same customId as the button. Therefore, when the button is pressed, it will call the "run" function defined within the InteractionHandler.
Result:
The InteractionHandler works for any components, as they all have a customId, and will therefore be called by the InteractionHandler.
Passing parameters:
The InteractionHandler also allows passing parameters to the callback in an extremely simplified manner. The following code demonstrates its usage.
import { ApplicationCommandType } from "discord.js";
import { CreateRow, CreateButton, InteractionHandler } from "ease-discord-js";
export default {
name: "test",
description: "command to test the library",
type: ApplicationCommandType.ChatInput,
run: async(client, interaction) => {
return interaction.reply({content: "Hello World!", components: [
new CreateRow([
new CreateButton({customId: "on_click_button:blue:primary", label: "Primary", style: "Primary"}),
new CreateButton({customId: "on_click_button:red:danger", label: "Danger", style: "Danger"})
])
]});
}
}
new InteractionHandler({
customId: "on_click_button",
useParams: true, // using this will pass the color and style as parameters to the callback function. You can also use this to pass other data
callback: async (client, interaction, color, style) => {
return interaction.reply({content: `You clicked the **${style}** button with the color **${color}**`, ephemeral: true});
}
})
In the code above, we see that the customId of the button is divided by ":" which separates the parameters for the InteractionHandler's callback. Therefore, in the InteractionHandler, you can define names for these parameters (in the example above, they are defined as color and style), and the response depends on these parameters as shown in the result below:
Simple, right? The next topic will show another way to receive interactions, this time by passing a function directly to the component.