Handling Application Commands
Interactions/Application Commands are the most important building block when it comes to discord bots nowadays. The goal of this guide is to teach you how you can create and respond to application commands using the default (raw) listeners.
If you would like you can also inject transformers to aid you doing this, refer to the transformers page for that.
Registering Commands
Registering an application command is the first step of this journey.
Using the setup
api
The recommended way of doing this is by using the setup
api, we talk more about why in this page.
1import type { Client } from "lilybird";2
3async function setup(client: Client): Promise<void> {4 // Lets register a command called 'ping'5 await client.rest.createGlobalApplicationCommand(client.user.id, {6 name: "ping",7 description: "pong"8 });9}
Creating the listener/handler for our commands
Above we created a command called ping
and now we want to handle it, lets create a simple handler to do this.
1import type {2 ApplicationCommandInteractionStructure,3 InteractionStructure,4 Client,5} from "lilybird";6
7async function handleCommand(8 client: Client,9 interaction: ApplicationCommandInteractionStructure10): Promise<void> {11 if (interaction.data.name === "ping") {12 const { ws, rest } = await client.ping();13 await client.rest.createInteractionResponse(interaction.id, interaction.token, {14 type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,15 data: {16 content: `🏓 WebSocket: \`${ws}ms\` | Rest: \`${rest}ms\``17 }18 });19 }20}
Putting everything together
Now, everything left for us to do is put it all together.
1import {2 InteractionType,3 createClient,4 Intents5} from "lilybird";6
28 collapsed lines
7import type {8 ApplicationCommandInteractionStructure,9 InteractionStructure,10 Client,11} from "lilybird";12
13async function setup(client: Client): Promise<void> {14 // Lets register a command called 'ping'15 await client.rest.createGlobalApplicationCommand(client.user.id, {16 name: "ping",17 description: "pong"18 });19}20
21async function handleCommand(22 client: Client,23 interaction: ApplicationCommandInteractionStructure24): Promise<void> {25 if (interaction.data.name === "ping") {26 const { ws, rest } = await client.ping();27 await client.rest.createInteractionResponse(interaction.id, interaction.token, {28 type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,29 data: {30 content: `🏓 WebSocket: \`${ws}ms\` | Rest: \`${rest}ms\``31 }32 });33 }34}35
36await createClient({2 collapsed lines
37 token: process.env.TOKEN,38 intents: [Intents.GUILDS],39 // We pass the setup function we created above40 setup,41 listeners: {42 interactionCreate: async (client, payload) => {43 // We only want to handle guild interactions44 if (!("guild_id" in payload)) return;45 // We only want to handle application commands46 if (payload.type !== InteractionType.APPLICATION_COMMAND) return;47
48 await handleCommand(client, payload);49 }50 }51});