Command Execution Process
To further understand this app let us understand how the command execution process
Receiving the command​
We are receiving commands from the Application INTERACTIONS ENDPOINT URL
More info :https://discord.com/developers/docs/interactions/receiving-and-responding#receiving-an-interaction
We are checking if the method is post in every request
// Check method
if (!allowedMethod(req, "POST")) return res.status(401).end("Method not allowed");
Verifying Discord Request​
we are using the verifyKey
function from discord interactions to verify that the request is coming from discord
// Verify discord request
const signature = req.headers["x-signature-ed25519"] as string | Uint8Array | ArrayBuffer | Buffer;
const timestamp = req.headers["x-signature-timestamp"] as string | Uint8Array | ArrayBuffer | Buffer;
const rawBody = await rawBodyToString(req);
const isValid = verifyKey(rawBody, signature, timestamp, PUBLIC_KEY);
if (!isValid) return res.status(401).end("invalid request");
Parsing Interaction Body​
We received the body as a rawBody using the rawBodyToString
function and we are again parsing it access it's data.
then we're checking if the interaction type is a ping this is needed in putting the INTERACTIONS ENDPOINT URL
on the discord application.
then if it's not a ping, we can assume that it is a application command.
// Parse body to get interaction data
const interactionNew = JSON.parse(rawBody) as APIInteraction;
// Check if the interaction type is a ping
// PING message, respond with ACK (part of Discord's security and authorization protocol)
if (interactionNew.type === InteractionType.Ping) return res.status(200).json({ type: 1 });
// If the interaction type is not a ping it is assumed to be a application command
const interaction = interactionNew as APIApplicationCommandInteraction;
Executing commands​
We then are fetching all of the commands using the getCommands
you can learn more about it in the utilities section. Then we run the execute function of the command
// get all commands
const allCommands = await getCommands();
// execute command
let reply: APIInteractionResponse | null = null;
const commandName = interaction.data.name + ".ts";
if (allCommands[commandName]) {
reply = await allCommands[commandName].execute(interaction);
}
if (!reply) throw new Error();
return res.status(200).json(reply);